简体   繁体   中英

React don't render mapping elements

I'm mapping Array and React don't want to render this. Typescript gives this error: " This JSX tag's 'children' prop expects a single child of type 'ReactNode', but multiple children were provided. ". But when I use React fragment in component instead of div error isn't detected. Why React don't render?

import { useDispatch, useSelector } from 'react-redux';

export const VkForm = () => {

    const messages = useSelector((state: appStateType) => state.MessageReducer.Messages)

    return (<div>
                {messages.map((m) => {
                    <div key={m._id}>{m.text}</div>
                })}
    </div>)

}

This is a common mistake for beginners. You are missing the actual return statement in your .map function.

Since you are using curly brackets you have to explicity add the return statement before your JSX Component like:

{messages.map((m) => {
    return <div key={m._id}>{m.text}</div>
})}

If you want to avoid explicitly returning that Component you can use the implicit return with parentheses:

{messages.map((m) => (
    <div key={m._id}>{m.text}</div>
))}

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