简体   繁体   English

在功能中设置状态不会触发重新渲染

[英]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)
}

As per DOC : 根据DOC

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视为不可变的。

Check the details about setState . 检查有关setState的详细信息。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM