In my state, I want to update an object property on the first item in an array of objects. The object property isn't changing, even though I am taking steps to ensure immutability.
this.state = {
myFruits: [{a: false, b: 2, c: 'apple'}, {'a': false, b: 4, c: 'kiwi'}, ...],
otherCategory: {}
}
/// further down the code in componentDidUpdate
{ myFruits } = this.state;
let copyFruits = [...myFruits];
let newFruit = { ...copyFruits[0], a : true };
// console.log(newFruit): {a: true, b: 2, c: 'apple'}
copyFruits[0] = newFruit;
// console.log(copyFruits[0)] = {a: true, b: 2, c: 'apple'}
this.setState({ myFruits: copyFruits });
// the end result is the same as the original state, where the first item, apple, has a : false instead of expected a : true
This change is being made in componentDidUpdate, and I'm not sure if this has any effect.
I guess the problem is that your componetDidUpdate method is not getting called. The code you have written here is perfectly fine.
class SolutionExample extends React.Component {
constructor(){
super()
this.state = {
myFruits: [{a: false, b: 2, c: 'apple'}, {'a': true, b: 4, c: 'kiwi'}],
otherCategory: {}
}
}
changeKey =() =>{
let { myFruits } = this.state;
let copyFruits = [...myFruits]
let newFruit = { ...copyFruits[0], a : true };
copyFruits[0] = newFruit;
this.setState({ myFruits: copyFruits });
}
componentDidUpdate()
{
// this method is called whenever the state is changed }
render() {
let { myFruits } = this.state;
return (
<div>
<h1>Solution</h1>
{myFruits.map((item) =>{
if(item.a){
return(<h2>{item.b + '-' + item.c}</h2>)
}
})}
<button onClick={this.changeKey}>Change state</button>
</div>
);
}
}
ReactDOM.render(<SolutionExample />, document.getElementById('example'));
Here is the link : https://codepen.io/anon/pen/pXYdWQ
You can simplify your change to:
const { myFruits } = this.state;
let newFruit = { ...myFruits[0], a : true };
this.setState({ myFruits: [newFruit, ...myFruits.splice(1)] });
Also, a better approach is to map
and update the object that you need by an id or any unique identifier.
this.setState({
myFruits: myFruits.map(fruit => {
if(fruit.c === "apple") {
fruit.a = true
return fruit;
}
return fruit;
})
})
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.