React - 组件返回函数内的条件渲染

Dar*_*res 5 reactjs

我想了解为什么反应会这样。

这有效

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} />
        ))}
      </>
Run Code Online (Sandbox Code Playgroud)

但这并不

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} />;
          }
        })}
      </>
Run Code Online (Sandbox Code Playgroud)

它只是返回空白。没有错误。

React 不渲染这个的原因是什么?仅渲染的最佳方法是什么post-1

小智 2

箭头函数语法可以接受要返回的值或要执行的代码块。在第一个示例中,您给出一个值:<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} />;
  }
})}
Run Code Online (Sandbox Code Playgroud)

或者将 if 更改为 && 以保持隐式返回行为:

{posts.map(post =>
  (post.id < 2) && <Post key={post.id} title={post.title} />
}
Run Code Online (Sandbox Code Playgroud)