简体   繁体   中英

Using Array.map in React

I'm confused how this code work

const sidebar = (
        <ul>
        {
            props.posts.map((post) =>
                <li key={post.id}>
                    {post.title}
                </li>
            )
        }
        </ul>
    );

I know that a map returns an array, but how can it return all these tags

<li key={post.id}>
    {post.title}
</li>

and render it?

I have tried changing it to forEach but it's not working. Nothing displays on the UI:

const sidebar = (
    <ul>
        {
            props.posts.forEach((post) =>{
                return <li key={post.id}>
                    {post.title}
                </li>
            })
        }
    </ul>
);

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The forEach() method executes a provided function once for each array element.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

This means if you try to return something in the method executed in forEach you are not creating an array of tags.

JSX is expecting an array of tags to be rendered but in forEach you are not creating an array you are just iterating over the array so JSX receives nothing at the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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