Reputation: 102
I am using picker-module in React native. I have to create a dataset for this. It is okay to write Dataset with my hand, but when I print it with for for a list, I get the following error. What is the solution?
//working
const dataset = [
{
value: "1",
label: "1",
},
{
value: "2",
label: "2",
},
{
value: "3",
label: "3",
}
]
//not working
for (let i = 0; i < 3; i++) {
this.setState({yearList:this.state.yearList.push({value:`${i}`,label:`${i}`})})
}
Upvotes: 2
Views: 52
Reputation: 180
The React docs says:
Treat this.state as if it were immutable.
Your push will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards. as an example, it could lead to that some lifecycle methods like componentDidUpdate won’t trigger.
The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
this.setState({
arrayvar: [...this.state.arrayvar, newelement]
})
Upvotes: 1