在函数中设置状态不会触发重新渲染

Setting state in function doesn't trigger a rerender

我想在用户登录时制作一个加载指示器,但由于某种原因 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>
    )
  }
}

为什么 waitingOnLogin 被 JSX 忽略了?

始终使用 setState 来更新 state 值,永远不要直接改变 state 值,使用这个:

handleLogin (event) {
    event.preventDefault()
    this.setState({ waitingOnLogin: true });
    this.props.userActions.login(this.state.email, this.state.password)
}

根据DOC

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

查看有关 setState 的详细信息。

不要直接使用 setState 改变状态。 setState 要求重新渲染,因此之后您的更改将反映出来,但直接分配不会发生 rerender,因此不会反映任何更改。此外,您应该始终使用 setState 来更改状态

handleLogin (event) {
    event.preventDefault()
    this.setState({waitingOnLogin:true});
    this.props.userActions.login(this.state.email, this.state.password)
  }