arrays - SetState 在数组中的对象属性上
问题描述
在我的状态下,我想更新对象数组中第一项的对象属性。对象属性没有改变,即使我正在采取措施确保不变性。
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'));
推荐阅读
- ruby - Chef - 在条件检查中嵌入模板块
- c# - 创建Entry的动态数组
- php - 通过 php 应用表单属性
- r - 使用 R 调用 API
- python - 如何更改图像大小以允许更长的音频(wav 到 png)
- sql - SQL Server 2017 - 使用多个序列创建唯一标识符,或者?
- javascript - API 请求被阻止,内容必须通过 HTTPS 提供
- python - 从交互式片段创建 python 脚本
- c# - SSIS VSTA:为什么在字典上使用 TryGetValue 时脚本组件调试器不起作用?
- javascript - 在单击时呈现选择标签 - REACT JS