状态改变不会重新渲染组件

发布于 2025-01-18 23:10:08 字数 927 浏览 1 评论 0原文

const [list, setList] = useState([]);
useEffect(() => {
        const getData = async () => {
            let storeList = [];
            for (let i = 0; i<50; i++) {
                try {   
                    const token = await contract.methods.tokenOfOwnerByIndex(accountId , i).call();
                    let data = await contract.methods.tokenURI(token).call();
                    const receivedData = await fetch(data);
                    let jsonData = await receivedData.json();
                    storeList.push(jsonData);
                    setList(storeList);
                } catch(error) {
                    cogoToast.error(`Error caused in fetching data of ${i} number token`);
                }
            }
        };
        if (contract) getData();
    }, [contract]);

“列表”的初始状态为空。当循环第一次运行并首次更新列表时,组件重新呈现,但是在此之后,即使状态更改组件也不会重新渲染。

理想情况下,当状态变化时,组件应重新渲染。

const [list, setList] = useState([]);
useEffect(() => {
        const getData = async () => {
            let storeList = [];
            for (let i = 0; i<50; i++) {
                try {   
                    const token = await contract.methods.tokenOfOwnerByIndex(accountId , i).call();
                    let data = await contract.methods.tokenURI(token).call();
                    const receivedData = await fetch(data);
                    let jsonData = await receivedData.json();
                    storeList.push(jsonData);
                    setList(storeList);
                } catch(error) {
                    cogoToast.error(`Error caused in fetching data of ${i} number token`);
                }
            }
        };
        if (contract) getData();
    }, [contract]);

the initial state of "list" is empty. When the loop is run for 1st time and the list is updated for the first time, the component re-renders, but after that, even though the state is changing the component does not re-render.

Ideally, the component should re-render when the state changes.

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

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

发布评论

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

评论(1

满地尘埃落定 2025-01-25 23:10:08

您正在改变已经存在的数组,而不是创建一个新数组。当你在函数组件中设置状态时,react 会在旧状态和新状态之间执行 === 。如果它们相同,则会跳过渲染。

要解决此问题,请创建一个新数组并使用该数组设置状态:

let jsonData = await receivedData.json();
setList(prev => [...prev, jsonData]);

You're mutating the array that already exists, not creating a new one. When you set state in a function component, react does a === between the old state and the new state. If they're the same, it skips rendering.

To fix this, create a new array and set state with that:

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