Do not mutate the state directly. Use state setState () response / no-direct-mutation-state

I have this code:

constructor(props) {
    super(props)
    this.state = {
        loginButton: '',
        benchmarkList: ''
    }
    if (props.username == null) {
        this.state.loginButton = <GoogleButton></GoogleButton>
    } else {

    }
}

This gives me an ESLint warning:

Do not mutate state directly. Use setState () to not react / non-direct-mutate-state.

Now, what should I do, because I can’t use setStateinside constructordirectly, since it creates error , and update as it gives me an error.

+4
source share
3 answers

First of all, we should not store the ui components inside the state variable , the state should contain only data. All part of ui should be inside the method render.

render - , . this.state.loginButton, null, .

:

constructor(props) {
    super(props)
    this.state = {
        loginButton: props.username,
        benchmarkList: ''
    }
}

render(){
    return(
        <div>
            {!this.state.loginButton ? <GoogleButton></GoogleButton> : null}
        </div>
    )
}

props state , this.props.username, , .

+3
constructor(props) {
    super(props)
    this.state = {
      loginButton: props.username == null? <GoogleButton></GoogleButton>: '',
      benchmarkList: ''
    }
  }

setState componentWillMount()

componentWillMount(){
   let loginButton = props.username == null? <GoogleButton></GoogleButton>: '';
   this.setState({loginButton: loginButton});
}
+5

constructor ReactJS?

, , :

constructor(props) {
    super(props)
    let state = {
        loginButton: '',
        benchmarkList: ''
    }
    if (props.username == null) {
        state.loginButton = true
    } else {
        state.loginButton = false
    }
    this.state = state
}
0

Source: https://habr.com/ru/post/1679461/


All Articles