![](/img/trans.png)
[英]reactJs setState change property on object within an array within an array
[英]SetState on object property in array
在我的狀態下,我想更新對象數組中第一項的對象屬性。 即使我正在采取措施確保不變性,對象屬性也不會改變。
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
此更改是在componentDidUpdate中進行的,我不確定這是否有效果。
我猜問題是您的componetDidUpdate方法沒有被調用。 您在此處編寫的代碼非常好。
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'));
這是鏈接: https : //codepen.io/anon/pen/pXYdWQ
您可以將更改簡化為:
const { myFruits } = this.state;
let newFruit = { ...myFruits[0], a : true };
this.setState({ myFruits: [newFruit, ...myFruits.splice(1)] });
另外,更好的方法是通過ID或任何唯一標識符map
和更新所需的對象。
this.setState({
myFruits: myFruits.map(fruit => {
if(fruit.c === "apple") {
fruit.a = true
return fruit;
}
return fruit;
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.