[英]Setting state in function doesn't trigger a rerender
I want to make a loading indicator on user login, but for some reason the JSX conditional element does not update: 我想在用户登录时创建一个加载指示器,但是由于某些原因,JSX条件元素不会更新:
class LoginPage extends Component {
constructor (props) {
super(props)
this.state = {
waitingOnLogin: false,
...
}
this.handleLogin = this.handleLogin.bind(this)
}
handleLogin (event) {
event.preventDefault()
this.state.waitingOnLogin = true
this.props.userActions.login(this.state.email, this.state.password)
}
render() {
return (
<div className='up'>
<form onSubmit={e => this.handleLogin(e)}> ... </form>
{this.state.waitingOnLogin && <Spinner message='Logging you in'/>} // This does not appear
</div>
)
}
}
Why does the waitingOnLogin
is being ignored by the JSX? 为什么JSX忽略了
waitingOnLogin
?
Always use setState
to update the state
value, never mutate the state
values directly, Use this: 始终使用
setState
更新state
值,切勿直接更改state
值,请使用以下命令:
handleLogin (event) {
event.preventDefault()
this.setState({ waitingOnLogin: true });
this.props.userActions.login(this.state.email, this.state.password)
}
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made.
切勿直接更改this.state,因为之后调用setState()可能会替换您所做的更改。 Treat this.state as if it were immutable.
将this.state视为不可变的。
Don't mutate state directly use setState
. 不要使用
setState
直接改变状态。 setState calls for rerender and hence after that your change will reflect but with direct assignment no rerender
occurs and thus no change is reflected. setState要求重新渲染,因此在此之后,您的更改将反映出来,但直接分配不会发生任何重新
rerender
,因此不会反映出任何更改。 Also you should always use setState
to change state 另外,您应该始终使用
setState
更改状态
handleLogin (event) {
event.preventDefault()
this.setState({waitingOnLogin:true});
this.props.userActions.login(this.state.email, this.state.password)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.