[英]How do I create a login form and response in React.js?
我正在使用 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 function 返回一個不在渲染方法中的 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>
不過,我不確定這是否是正確的方法。 我通常使用 react-router在他們的文檔中建議的變體
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.