如果元素为null,如何不呈现?

时间:2019-04-16 13:07:19

标签: javascript reactjs

我想呈现新闻提要。文章可以包含标题,图片和作者姓名。我这样渲染:

render() {
    const newsItem = (article, id) => (
      <article className="news-item" key={id}>
        <img className="news-picture" src={`${article.urlToImage}`} alt=""/>
        <h1 className="news-title">{article.title}</h1>
        <p>Author: {article.author}</p>
      </article>
    );

    const newsFeed = this.state.news.map(e => newsItem(e, pushid()));

    return (
      <div className="news-feed">{newsFeed}</div>
    );
  }
}

有时API不提供作者姓名(该值为null),如果是这样,我就不想呈现

<p>Author: {article.author}</p>

如何在反应中正确完成?

3 个答案:

答案 0 :(得分:3)

尝试一下:

{article.author && <p>Author: {article.author}</p>}

这意味着如果article.author存在或不为null,则呈现<p>...</p>

这与if语句相同,除了您不能在此处编写if语句。就是那个。

if(article.author) return <p>Author: {article.author}</p>

答案 1 :(得分:2)

只需使用short circuiting &&

检查是否存在
{ article.author &&  <p>Author: {article.author}</p> }

它如何工作?

x && y
|
|___________ if x true move ahead and execute `y` else don't

答案 2 :(得分:0)

render() {
const newsItem = (article, id) => {
  if (!article.author) {
    return null;
  }
  <article className="news-item" key={id}>
    <img className="news-picture" src={`${article.urlToImage}`} alt=""/>
    <h1 className="news-title">{article.title}</h1>
    <p>Author: {article.author}</p>
  </article>

};

const newsFeed = this.state.news.map(e => newsItem(e, pushid()));

return (
  <div className="news-feed">{newsFeed}</div>
);

} }

只需设置上述if条件。 因此,如果它为null,则可以返回null。