我有一个对象数组,该对象保存到userList useState中,该用户列表由以下内容组成:
[{
firstName: "blah"
lastName: "blah2"
}
{
firstName: "test"
lastName: "test2"
}]
我有一个useEffect,它调用一个函数并返回一个值。我想在userList中为每个用户存储一个新的键和值。
useEffect(() => {
userList.forEach((user, index) =>
returnNewValueForNewKeyFunction(user, index).then(newValue => {
userList[index]['newKey'] = newValue
//this console.log shows new field and value
console.log(userList)
//this console.log ALSO shows new field and value
console.log(JSON.stringify(contactList[index]))
})
)
}
}, [])
如果我不在console.log中操作,这很好,但是不幸的是,我需要将数据呈现到页面上。在我的呈现器中,我有:
return (
<TableBody>
{userList
.map((user, index) => (
<TableRow>
<TableCell>
{user.newKey}
</TableCell>
)
user.newKey显示为空白,并且似乎根本没有更新用户。我该如何做才能使值实际更新并在渲染时可以读取?
答案 0 :(得分:2)
您不应该对列表进行变异,应该使用useState来存储列表,所以类似这样:
const [ state, setState] = useState(userList);
然后,当您要更新时,请执行以下操作:
const listCopy = [...state];
//Logic to update your list here
listCopy[index][otherindex] = Value;
setState(listCopy)
希望这会有所帮助
答案 1 :(得分:0)
您正在修改userList
,但没有调用set
函数,这意味着React将不知道如何使用更新后的状态重新渲染。
您应该创建一个新数组,而不是更改当前状态,然后在进行更改后使用更新后的数组调用set
返回的useState
函数。
看起来您的returnNewValueForNewKeyFunction
是一个诺言/ async
,这意味着您的每个商品更改都在发生async
。您需要使这些同步/等待所有更新,然后再更新状态,以使状态更改一次UI更新。
例如,将两者放在一起-如果您正在这样做:
const [userList, setUserList] = useState();
您可以这样做:
useEffect(() => {
// Since can't use an async func directly with useEffect -
// define an async func to handle your updates and call it within the useEffect func
const updateUsers = async () => {
// Create a new array for your updated state
const updatedUserList = [];
// Loop over your values inline so your can await results to make them sync
for (let index = 0; index < userList.length; index ++) {
const user = userList[index];
const newVal = await returnNewValueForNewKeyFunction(user, index);
// Create a shallow copy of the original value and add the newValue
updatedUserList[index] = { ...user, newKey: newValue };
// ... Any other logic you need
}
// Call set with the updated value so React knows to re-render
setUserList(updatedUserList);
};
// Trigger your async update
updateUsers();
}, [])