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
79 views
in Technique[技术] by (71.8m points)

javascript - What's wrong with passing a react functional component to .map()?

Say that I have a component, Todo. It takes props title and dueDate. In a container component, I might map over some todos like this:

todos = [
  { title: "Read a book", dueDate: new Date() }
  // etc...
]

// ... later in the code ...

todos.map(x => <Todo title={x.title} dueDate={x.dueDate} />)

But, surely I could also just do this:

todos.map(Todo)

for the same result?

I haven't seen this in any tutorials or anything so I'm wondering what's wrong with this approach instead of the verbose alternative.

question from:https://stackoverflow.com/questions/65884157/whats-wrong-with-passing-a-react-functional-component-to-map

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

1 Reply

0 votes
by (71.8m points)

But, surely I could also just do this:

todos.map(Todo)

No, those are two different things. .map(x => <Todo title={x.title} dueDate={x.dueDate}/>) calls React.createElement to create the Todo, but just .map(Todo) simply calls Todo directly.

You need to create the element, not just call the function. Those are fundamentally different things. <Todo ... /> doesn't call Todo at all, it just calls React.createElement, which will remember the Todo function and call it as/when necessary. This doesn't call Todo, for instance:

// Doesn't call `Todo`, just remembers it
const el = <Todo title={x.title} dueDate={x.dueDate}/>;

Later, if we use el in another component or with ReactDOM.render or similar, then Todo will be called as necessary.

...instead of the verbose alternative.

If you're looking for something more concise, as jonrsharpe pointed out, you can do .map(x => <Todo {...x}/>)


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

...