【问题标题】:React doesn't render array objectsReact 不渲染数组对象
【发布时间】:2023-01-13 23:23:47
【问题描述】:

我正在尝试制作一个等待数组被填充然后将其传递给setData() 函数的程序。数据必须在之后呈现。但由于某些原因,尽管数组已满,但反应并未呈现它,正如我从控制台中看到的那样。

import { useEffect, useState } from 'react';

export default function EntitiesRecognized(props) {

    const [isLoading, setLoading] = useState(true);
    const [data, setData] = useState([]);

    const call_razor = async (sentence) => {
        try {
            return new Promise((resolve, reject) => {
                setTimeout(() => {resolve('200' + sentence)}, 2000)
            })
        } catch (err) {
            console.log(err)
        }   
    }

    useEffect(() => {
        const dataFetch = async () => {
            let arr = [];
            await props.props.map(async prop => {
                console.log(prop)
                await call_razor(prop).then(response => arr.push(response))
            });
            setData(arr);
            setLoading(false);
        };
        dataFetch();
    }, []);

    return (
        <div>
            {isLoading
                ? <h1>Loading</h1>
                : data.map((sentence, idx) => {
                    return <h5 key={idx}>{sentence}<hr/></h5>
                })
            }
        </div>
    );
};

它没有显示任何错误,只是一个空白页面。

【问题讨论】:

    标签: reactjs arrays async-await rendering


    【解决方案1】:
    await props.props.map(async prop => {
    

    .map 返回一个数组,而不是一个承诺,所以 awaiting 它什么都不做。因此,您几乎立即越过此行,然后使用仍然为空的数组调用 setData。 React 渲染那个空数组,所以屏幕上没有任何内容。稍后,您改变数组以包含内容,但 React 不知道您这样做了并且不会重新渲染,除非您再次设置状态。

    我建议你做出一系列承诺,然后使用 Promise.all 将它们组合成一个承诺,然后 await 得到完成的数组:

    const dataFetch = async () => {
      const promises = props.props.map(prop => call_razor(prop))
      const arr = await Promise.all(promises);
      setData(arr);
      setLoading(false);
    }
    

    【讨论】:

    • 这么愚蠢的错误。谢谢,它成功了;)
    猜你喜欢
    • 2019-11-15
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 2019-03-19
    • 2020-03-03
    • 1970-01-01
    相关资源
    最近更新 更多