React中的对象数组的SetState [英] SetState of an array of Objects in React
本文介绍了React中的对象数组的SetState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,所以我很沮丧地找到正确的解决方案,所以我在这里发布了问题.给出答案将对我有很大帮助,因为我被卡住了!
Ok, so I'm so frustrated finding the right solution so I'm posting the problem here. Giving an answer would help me a lot, coz I'm stuck!
状态树看起来像这样
this.state = {
itemList : [{
_id : 1234,
description : 'This the description',
amount : 100
}, {
_id : 1234,
description : 'This the description',
amount : 100
}],
}
问题是:
- 无法根据以下条件更新数组的对象中的任何特定键 到_id
- 以前的状态应保持不变
- can not update any specific key in the Object of the array according to the _id
- The previous state should remain intact
推荐答案
于2018年3月25日回答
这是使用setState和prevstate更新数据结构中对象的某些属性的方法.
answered March 25 2018
This is how you would use setState and prevstate to update a certain attribute of an object in your data structure.
this.setState(prevState => ({
itemList: prevState.itemList.map(
obj => (obj._id === 1234 ? Object.assign(obj, { description: "New Description" }) : obj)
)
}));
已回答2019年12月12日(REOK HOOKS)
import React, { useState } from 'react';
const App = () => {
const [data, setData] = useState([
{
username: '141451',
password: 'password',
favoriteFood: 'pizza',
},
{
username: '15151',
password: '91jf7jn38f8jn3',
favoriteFood: 'beans'
}
]);
return (
<div>
{data.map(user => {
return (
<div onClick={() => {
setData([...data].map(object => {
if(object.username === user.username) {
return {
...object,
favoriteFood: 'Potatos',
someNewRandomAttribute: 'X'
}
}
else return object;
}))
}}>
{JSON.stringify(user) + '\n'}
</div>
)
})}
</div>
)
}
这篇关于React中的对象数组的SetState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文