当 React Redux 的用户提要中没有帖子时如何显示消息?

How to show the message when there are no posts in user feed in react redux?

现在,如果我转到显示 post 列表的提要。所以,当没有 post 时,我想显示 No posts found 消息。我正在通过 mapStateToProps.

获得 isFetchingposts

posts是reducer中的数组字段,初始状态为空。因此,当没有创建 post 时,数组为空。

如何显示消息?

  render() {
    const { isFetching, posts  } = this.props

    return isFetching ? (
      <p>Fetching....</p>
    ) : (
      <div>
        {posts &&
          posts.map((post) => {
            return <Cards key={post._id} post={post} />
          })}
      </div>
    )
    ```

与检查 isFetching 的方式相同,但使用 posts.length != 0.

return isFetching ? (
    <p>Fetching....</p>
) : (
    <div>
        {(posts && posts.length != 0) ?
            posts.map((post) => { 
                return <Cards key={post._id} post={post} />
            }) : <p>No posts found</p>}
    </div> 
)

在这种情况下,您可以使用 condition operators

return isFetching ? (
      <p>Fetching....</p>
    ) : (
      <div>
        { posts 
            ? ( 
                posts.map((post) => {
                return <Cards key={post._id} post={post} />
               ): (
               <div> No posts found</div>
               )
          })
        }
      </div>
    )

您可以根据需要使用 if else 进行渲染。

render() {
  const { isFetching, posts } = this.props

  if (isFetching) {
    return <p>Fetching...</p>;
  } else if (!posts && posts.length) {
    return <p>No posts found</p>
  } else {
    return (
      <div>
        {posts.map(post => <Cards key={post._id} post={post} />)}
      </div>
    );
  }
}

注意:也可以使用三进制,但我想,if 在这里看起来更易读。