I have this code:
constructor(props) {
super(props)
this.state = {
loginButton: '',
benchmarkList: ''
}
if (props.username == null) {
this.state.loginButton = <GoogleButton></GoogleButton>
} else {
}
}
It is giving me an ESLint warning:
Do not mutate state directly. Use setState() react/no-direct-mutation-state.
Now what am I supposed to do as I can't use setState
inside constructor
directly as it creates error and updating like this gives me error.
I have this code:
constructor(props) {
super(props)
this.state = {
loginButton: '',
benchmarkList: ''
}
if (props.username == null) {
this.state.loginButton = <GoogleButton></GoogleButton>
} else {
}
}
It is giving me an ESLint warning:
Do not mutate state directly. Use setState() react/no-direct-mutation-state.
Now what am I supposed to do as I can't use setState
inside constructor
directly as it creates error and updating like this gives me error.
4 Answers
Reset to default 8First of all, we should not store the ui components inside state variable, state should contain only data. All the ui part should be inside render
method.
If you want to render
some component on the basis of any data then use conditional rendering. Check the value of this.state.loginButton
and if it is null
then render that button.
Like this:
constructor(props) {
super(props)
this.state = {
loginButton: props.username,
benchmarkList: ''
}
}
render(){
return(
<div>
{!this.state.loginButton ? <GoogleButton></GoogleButton> : null}
</div>
)
}
Ideally we should not store the props
value in state
also, so directly use this.props.username
, i did that because don't know about the complete code.
constructor(props) {
super(props)
this.state = {
loginButton: props.username == null? <GoogleButton></GoogleButton>: '',
benchmarkList: ''
}
}
Or You can use setState in componentWillMount()
componentWillMount(){
let loginButton = props.username == null? <GoogleButton></GoogleButton>: '';
this.setState({loginButton: loginButton});
}
How to update state inside
constructor
in ReactJS?
Create the data struct, modify it as need, and assign to state at the end when all is done:
constructor(props) {
super(props)
let state = {
loginButton: '',
benchmarkList: ''
}
if (props.username == null) {
state.loginButton = true
} else {
state.loginButton = false
}
this.state = state
}
just add setState
if (props.username == null) {
this.setState({
loginButton: <GoogleButton></GoogleButton>
})
} else {
this.state
doesn't have to be the first statement; you can set all kinds ofvar
s first, then use those to composethis.state
. – user5734311 Commented Jun 16, 2017 at 14:12{ !this.state.username && <GoogleButton /> }
in your render object. – user5734311 Commented Jun 16, 2017 at 14:14render()
method. I can't remember off the top of my head, but there are a few other gotchas I remember reading about, too. – rossipedia Commented Jun 16, 2017 at 14:26