用户登录后,我试图将我的应用重定向到“ home”。我确实有一个onSubmitSignin函数,该函数会评估登录凭据(来自页面上的临时数据库),然后运行onRouteChange函数,该函数应该将路线更改为“家”,但出现错误“ this.setState不是函数”。
新来的反应,肯定有一些我不明白的地方。任何见解将不胜感激,谢谢!
App.js代码:
const initialState = {
route: 'signin',
isSignedIn: false
}
class App extends Component {
constructor(props){
super(props);
this.state = initialState;
}
onRouteChange (route) {
if (route === 'signout') {
this.setState({initialState});
} else if (route === 'home') {
this.setState({isSignedIn: true})
}
this.setState({route: route})
}
render () {
const { isSignedIn } = this.state;
return (
<div className="App">
<Navigation onRouteChange={this.onRouteChange} />
{isSignedIn ? <Account /> : <Signin onRouteChange={this.onRouteChange}/> }
</div>
);
}
}
export default App;
登录代码:
et database = {
email: 'test@gmail.com',
password: 'test'
}
class Signin extends React.Component {
constructor(props){
super(props);
this.state = {
signInEmail: '',
signInPassword: ''
}
}
onEmailChange = (event) => {
this.setState({signInEmail: event.target.value})
}
onPasswordChange = (event) => {
this.setState({signInPassword: event.target.value})
}
onSubmitSignIn = (e) => {
e.preventDefault();
if (this.state.signInEmail === database.email && this.state.signInPassword === database.password) {
this.props.onRouteChange('home');
} else {
return (this.props.onRouteChange('signout'));
}
}
render () {
return (
<div className="form">
<form>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input onChange ={this.onEmailChange} type="email" className="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email"/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input onChange ={this.onPasswordChange} type="password" className="form-control" id="password" placeholder="Password"/>
</div>
<div className="signInButton">
<button onClick={this.onSubmitSignIn} type="submit" className="btn btn-secondary">Sign in</button>
</div>
</form>
</div>
)
}
}
export default Signin;
You need to bind the context of
this
of youronRouteChange
function in constructor to your component otherwise this will be undefined.Or you can convert your function to an arrow function. Arrow function doesn't create it's own instance of this so it's
this
will point to your class.这是绑定和失去作用域的问题:
Due to the below line you are losing scope of the
this
,解决方案:
您可以在构造函数中绑定函数
要么
使用箭头功能