Setting state in function doesn't trigger a re

2020-05-08 06:05发布

问题:

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.