Setting state in function doesn't trigger a rerender

萝らか妹 提交于 2019-12-02 14:33:17

问题


I want to make a loading indicator on user login, but for some reason the JSX conditional element does not update:

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?


回答1:


Don't mutate state directly use 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. Also you should always use setState to change state

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



回答2:


Always use setState to update the state value, never mutate the state values directly, Use this:

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

As per DOC:

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

Check the details about setState.



来源:https://stackoverflow.com/questions/44002247/setting-state-in-function-doesnt-trigger-a-rerender

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!