Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

javascript - 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.

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. I assume is being rendered before the data is fetched?

My data fetching function looks like this:

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? 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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to put the renderData method in the return of your functional Component.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...