我正在使用React.js、React bootstrap和javascript。
我正在尝试创建一个登录页面。因此,当用户键入url时:www.example.com/
-他们到达登录页面,当他们输入www.example.com/line-chart
时也是如此
除非用户登录,否则当键入www.example.com/line-chart
时,用户将看到一个折线图。
我的登录表单如下
<Form className="login-form p-3" onSubmit={handleSubmit}>
<Form.Group controlId="formUsername">
<Form.Label>Username</Form.Label>
<Form.Control
type="text"
placeholder="Username"
onChange={e => setUsername(e.target.value)}
/>
</Form.Group>
<Form.Group>
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
onChange={e => setPassword(e.target.value)}
/>
</Form.Group>
<Button
className="mt-5 mb-3"
variant="primary"
disabled={!validateForm()}
type="submit"
>
Submit
</Button>
</Form>
我的句柄提交看起来像这样
function handleSubmit(event){
event.preventDefault()
let accountExists = false
//checks if account exists
for(let i = 0; i < mockData.userName.length; i++){
let userNameExists = (mockData.userName[i] === username) ? true: false;
let passwordExists = (mockData.password[i] === password) ? true: false;
if(passwordExists && userNameExists){
accountExists = true
}
}
if(accountExists){
props.updateAuthenticationAndRedirect()
debugger
}
}
我的应用程序如下
constructor(props){
super(props)
this.state = {
isAuthenticated:false,
redirectURL:"line-chart"
}
this.updateAuthenticationAndRedirect = this.updateAuthenticationAndRedirect.bind(this)
}
updateAuthenticationAndRedirect(){
this.setState( (state, props) => ( { isAuthenticated:true } ), () =>{
return <Redirect to="/line-chart" />
})
}
render(){
return(
<Router>
<Switch>
<Route
exact
path="/line-chart"
render={ () => (this.state.isAuthenticated) ? <LineChart /> : <Redirect to="/" /> }
/>
<Route exact path="/" >
<Login
authenticated={this.state.isAuthenticated}
updateAuthenticationAndRedirect={this.updateAuthenticationAndRedirect}
redirectURL={this.state.redirectURL}
/>
</Route>
</Switch>
</Router>
)
}
我不确定从哪里开始任何帮助都将不胜感激,谢谢
我认为问题出在updateAuthenticateionAndRedirect((方法上。您从不在呈现方法内的javascript函数返回一个JSX元素:return <Redirect to="/line-chart" />
为了使您的实现工作,您还需要在登录路径中添加一个检查,如下所示:
<Route
exact
path="/"
render={() => {
!this.state.isAuthenticated ?
<Login
authenticated={this.state.isAuthenticated}
updateAuthenticationAndRedirect={this.updateAuthenticationAndRedirect}
redirectURL={this.state.redirectURL}
/> :
<Redirect to="/line-chart" />
}
>
<Login
/>
</Route>
虽然我不确定,如果这是正确的方法。我通常使用反应路由器在他们的文档中建议的变化