I'm new to React, and I'm trying to figure out how to setState to the object, but it doesn't work when I this.setState({ datasets[0].data: }), in the function what do I need to do here??
state={
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
data: [0, 10, 5, 2, 20, 30, 45],
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
}]
}
change = () => {
this.setState({
datasets:
})
}
this.setState((prevState) => {
const datasets = prevState.datasets;
datasets[0].label = newLabel; //you can change particular value this way
return {datasets};
});
What this does is actually make a copy of prevState datasets array of objects and the mutates its value as per the requirement. Once the changes are done, we will setState value with the value of the updated datasets.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.