简体   繁体   English

无法在 React 中的数组上进行 map

[英]Cannot map over array in React

I'm passing an array (data) to the component via a prop, but then I can't map over data.我通过一个道具将一个数组(数据)传递给组件,但是我不能通过数据进行 map。

const Component1 = ({ data }) => {

  console.log(data);

  const renderData = () =>
      data.map(singleItem => (
          <OtherComponent key={singleItem ._id} singleItem ={singleItem} />
      ));

return (
            <Row className="row--small-padding">{renderData()}</Row>
    );

console.log(data) returns array of objects as expected, however, the data is not being passed to another component. console.log(data)按预期返回对象数组,但是,数据没有传递给另一个组件。 I assume is being rendered before the data is fetched?我假设在获取数据之前正在渲染?

My data fetching function looks like this:我获取 function 的数据如下所示:

const fetchAllData = async () => {
        const response = await getData();
        const data = await response;
        setData(data);
    };

    useEffect(() => {
        fetchAllData();
    }, []);

I have worked this around by adding data && before the map function, but the data is being passed through many components and I would like to know if there is any other solution for this?我已经通过在 map function 之前添加data &&来解决这个问题,但是数据正在通过许多组件传递,我想知道是否还有其他解决方案? How do I set my components to wait for data to be fetched and then render?如何设置我的组件以等待获取数据然后渲染?

Edit: data array initial state is set to null, like this:编辑:数据数组初始 state 设置为 null,如下所示:

const Component= () => {
    const [data, setData] = useState(null);

    const fetchAllData = async () => {
        const response = await getData();
        const data = await response;
        setSources(data);
    };

    useEffect(() => {
        fetchAllData();
    }, []);

    return (
        <>
            <Component1 limit={4} data={data} />
            <Component2 limit={4} data={data} />
            <Component3 limit={4} data={data} />
        </>
    );
};

export default Component

You have to put the renderData method in the return of your functional Component .您必须将renderData方法放在功能Component的返回中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM