reactjs React不呈现数组对象

qnakjoqk  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(187)

我正在尝试做一个程序,等待数组被填充,然后将其传递给setData()函数。数据必须在之后呈现。但由于某些原因,react没有呈现它,尽管事实上数组是满的,正如我可以从控制台看到的。

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>
    );
};

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

e0bqpujr

e0bqpujr1#

await props.props.map(async prop => {

.map返回一个数组,而不是一个承诺,所以await ing它什么也不做。所以你几乎立即跳过这一行,然后用一个仍然为空的数组调用setData。React呈现这个空数组,所以屏幕上什么也没有。稍后,你修改数组以包含内容,但是react不知道你做了这个,除非你再次设置state,否则不会重新呈现。
我建议你做一个promise数组,然后使用Promise.all把它们组合成一个promise,然后使用await that得到完成的数组:

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

相关问题