簡體   English   中英

將鍵/值對添加到現有對象數組

[英]Add key/value pair to existing array of objects

我有一組對象保存到 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 顯示為空白,似乎用戶根本沒有更新。 我怎樣才能使值實際更新並且可以在渲染時讀取?

你不應該改變你的列表,你應該使用 useState 來存儲你的列表,所以像這樣:

const [ state, setState] = useState(userList);

然后當你想更新時,做這樣的事情:

const listCopy = [...state];
//Logic to update your list here
listCopy[index][otherindex] = Value;
setState(listCopy)

希望這可以幫助

你正在修改你的userList但沒有調用你的set函數,這意味着 React 不知道要用更新后的狀態重新渲染。

您應該創建一個新數組,然后在進行更改后使用更新后的數組調用useState返回的set函數,而不是改變當前狀態。

看起來您的returnNewValueForNewKeyFunction是一個 promise / 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();
}, [])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM