React 重新渲染“错误”数据

发布于 2025-01-14 12:40:09 字数 2279 浏览 1 评论 0原文

我有一个 React 应用程序,其中包含一个从 API 获取数据并呈现它的列表。单击按钮即可更新此列表(获取更多数据)。我希望在“新”数据进入之前清除列表。 因为我的问题是在一个相当大的应用程序中,所以我尝试抽象地解释它: 这是我当前的(抽象)代码:

import React, { useState } from 'react'

const MyList = () => {

    const agesToFetch = [18, 19, 20, 21]
    const [listItems, setListItems] = useState({ "test1": false, "test2": true })

    const updateList = () => {
        // clearing list
        setListItems({})

        agesToFetch.forEach(age => {
            // AJAX request (sending age and some form input and recieving a name with a boolean)
            // for different inputs different results (simulated with random number)
            const result1 = {}
            result1["test" + Math.random().toString().substr(15)] = false
            setListItems({...listItems, result1}) // but here it takes the old already removed state value :(

            const result2 = {}
            result2["secondstest" + Math.random().toString().substr(15)] = false
            setListItems({...listItems, result2}) // here too
        })
    }

    return (
        <>
            <button onClick={updateList}>Update</button>
            < table >
                <thead>
                    <tr>
                        <th>Name </th>
                        < th > reachable </th>
                    </tr>
                </thead>
                < tbody >
                    {
                        Object.keys(listItems).map(name => {
                            const reachable = listItems[name]
                            return (
                                <tr style={{ "opacity": reachable ? "1" : "0.5" }
                                }>
                                    <td>{name} </td>
                                    < td > {reachable ? "reachable" : "NOT reachable"} </td>
                                </tr>
                            )
                        }
                        )
                    }
                </tbody>
            </table>
        </>
    )
}

export default MyList

状态在开始时有一些值并被清除,但该函数使用状态值(尚未清除)。因此,在本例中为 test1 和 test2 的“旧”值。

如何防止这种情况发生?

I have a React App which includes a list that fetches data from an API an renders it. With a button-click this list can be updated (fetching some more data). I want the list to be cleared before the "new" data comes in.
Because my problem is in a pretty big app, I try to explain it abstractly:
Here is my current (abstract) code:

import React, { useState } from 'react'

const MyList = () => {

    const agesToFetch = [18, 19, 20, 21]
    const [listItems, setListItems] = useState({ "test1": false, "test2": true })

    const updateList = () => {
        // clearing list
        setListItems({})

        agesToFetch.forEach(age => {
            // AJAX request (sending age and some form input and recieving a name with a boolean)
            // for different inputs different results (simulated with random number)
            const result1 = {}
            result1["test" + Math.random().toString().substr(15)] = false
            setListItems({...listItems, result1}) // but here it takes the old already removed state value :(

            const result2 = {}
            result2["secondstest" + Math.random().toString().substr(15)] = false
            setListItems({...listItems, result2}) // here too
        })
    }

    return (
        <>
            <button onClick={updateList}>Update</button>
            < table >
                <thead>
                    <tr>
                        <th>Name </th>
                        < th > reachable </th>
                    </tr>
                </thead>
                < tbody >
                    {
                        Object.keys(listItems).map(name => {
                            const reachable = listItems[name]
                            return (
                                <tr style={{ "opacity": reachable ? "1" : "0.5" }
                                }>
                                    <td>{name} </td>
                                    < td > {reachable ? "reachable" : "NOT reachable"} </td>
                                </tr>
                            )
                        }
                        )
                    }
                </tbody>
            </table>
        </>
    )
}

export default MyList

The state has some values in the beginning and gets cleared, but the function uses the state value (which isn't cleared yet). So the "old" values, in this example test1 and test2.

How can I prevent that from happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮年 2025-01-21 12:40:09

您没有正确设置状态,您应该使用 prev 进行设置:

    setListItems(prevState => ({
            ...prevState,
            result1
        }));

You are not setting state properly, you should do it with prev:

    setListItems(prevState => ({
            ...prevState,
            result1
        }));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文