React中对象数组的SetState
SetState of an array of Objects in React
好的,所以我很沮丧地找到正确的解决方案,所以我将问题发布在这里。给出答案会对我有很大帮助,因为我被困住了!
状态树看起来像这样
this.state = {
itemList : [{
_id : 1234,
description : 'This the description',
amount : 100
}, {
_id : 1234,
description : 'This the description',
amount : 100
}],
}
问题是:
- 无法更新数组对象中的任何特定键
到 _id
- 之前的状态应该保持不变
执行此操作的唯一方法是复制 itemList,对其进行修改,然后为其设置状态。
update() {
let itemList = this.state.itemList.slice();
//update it
this.setState({ itemList });
}
要更新这样构造的状态,您必须找到要更新的元素的索引,复制数组并更改找到的索引。
如果将记录列表作为对象保存,将 id 作为键,将记录作为值,这样会更容易、更易读。
2018 年 3 月 25 日回答
这就是您将如何使用 setState 和 prevstate 更新数据结构中对象的特定属性。
this.setState(prevState => ({
itemList: prevState.itemList.map(
obj => (obj._id === 1234 ? Object.assign(obj, { description: "New Description" }) : obj)
)
}));
2019 年 12 月 12 日回答(REACT 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>
)
}
将数据更新为对象数组的最佳方式
onChange={ (e) => this.setState({formData: { ...this.state.formData, 'plan_id': e.target.value}})}
好的,所以我很沮丧地找到正确的解决方案,所以我将问题发布在这里。给出答案会对我有很大帮助,因为我被困住了!
状态树看起来像这样
this.state = {
itemList : [{
_id : 1234,
description : 'This the description',
amount : 100
}, {
_id : 1234,
description : 'This the description',
amount : 100
}],
}
问题是:
- 无法更新数组对象中的任何特定键 到 _id
- 之前的状态应该保持不变
执行此操作的唯一方法是复制 itemList,对其进行修改,然后为其设置状态。
update() {
let itemList = this.state.itemList.slice();
//update it
this.setState({ itemList });
}
要更新这样构造的状态,您必须找到要更新的元素的索引,复制数组并更改找到的索引。
如果将记录列表作为对象保存,将 id 作为键,将记录作为值,这样会更容易、更易读。
2018 年 3 月 25 日回答
这就是您将如何使用 setState 和 prevstate 更新数据结构中对象的特定属性。
this.setState(prevState => ({
itemList: prevState.itemList.map(
obj => (obj._id === 1234 ? Object.assign(obj, { description: "New Description" }) : obj)
)
}));
2019 年 12 月 12 日回答(REACT 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>
)
}
将数据更新为对象数组的最佳方式
onChange={ (e) => this.setState({formData: { ...this.state.formData, 'plan_id': e.target.value}})}