我想了解为什么反应是这样的。
这行得通
class Feed extends React.Component {
constructor(props) {
super(props);
}
render() {
const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
return (
<>
{posts.map(post => (
<Post key={post.id} title={post.title} />
))}
</>但这不是
class Feed extends React.Component {
constructor(props) {
super(props);
}
render() {
const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
return (
<>
{posts.map(post => {
// changes are here
if (post.id < 2) {
<Post key={post.id} title={post.title} />;
}
})}
</>它只是返回空白。没有错误。
为什么反应没有呈现出来呢?只有呈现post-1的最佳方法是什么?
发布于 2018-11-13 03:31:12
箭头函数语法可以接受要返回的值,也可以接受要执行的代码块。在第一个例子中,您提供了一个值:<Post key={post.id} title={post.title} />。但是,在第二个示例中,您将给出一个代码块(使用{})。因此,您需要在return之前添加<Post key={post.id} title={post.title}>,如下所示:
{posts.map(post => {
if (post.id < 2) {
return <Post key={post.id} title={post.title} />;
}
})}或将if更改为&&以保持隐式返回行为:
{posts.map(post =>
(post.id < 2) && <Post key={post.id} title={post.title} />
}发布于 2018-11-13 03:22:06
您必须将其更改为return <Post ... />;
发布于 2018-11-13 03:33:32
您没有在函数参数中返回任何内容。您可以使用三元表达式和使用es6箭头表示法轻松地做到这一点。
posts.map(post => (post.id < 2) ? <Post key={post.id} title={post.title} /> : null)https://stackoverflow.com/questions/53273283
复制相似问题