反应条件渲染 [英] React Conditional Rendering

查看:57
本文介绍了反应条件渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出React中的条件渲染.如果用户的监视列表中没有电影,我只想输出一个标题.我以为这样的事情会起作用:

I'm trying to figure out conditional rendering in React. If there are no movies in the user's watchlist, i just want to output a title. I thought somethin like this would work:

render() {
    return (
        <Container>
            {this.state.watchlist.map(item => {
                if(this.state.watchlist.length > 0) {
                    return (
                        <WatchlistMovie
                            className="watchlist-movie"
                            key={item.id}
                            id={item.id}
                            title={item.title}
                            poster={item.poster}
                            overview={item.overview}
                            rating={item.rating}
                            user={this.props.user}
                        />
                    );
                } else {
                    return <h1>no movies</h1>
                }
            )}}
        </Container>
    );
}

推荐答案

我相信您希望 map

  <Container>
    {this.state.watchlist.length === 0 && <h1>no movies</h1>}

    {this.state.watchlist.map(item => (<WatchlistMovie
      className="watchlist-movie"
      key={item.id}
      id={item.id}
      title={item.title}
      poster={item.poster}
      overview={item.overview}
      rating={item.rating}
      user={this.props.user}
    />))}

  </Container>

这篇关于反应条件渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆