【问题标题】:How can i get the values of actor names from the below given json. I am able to get rest of the values but not actor names如何从下面给定的 json 中获取演员名称的值。我能够得到其余的值,但不能得到演员的名字
【发布时间】:2020-08-23 02:29:22
【问题描述】:

这就是我的 JSON 响应的样子。我可以获取 id 和 title 等的值,但不能获取 actor,因为 actor 是 json 对象内的另一个数组。 下面是我的反应代码的样子。我尝试了几个选项,但总是以未定义属性的错误告终。

```
    {
    actor: [
    {
    name: "Leonardo DiCaprio"
    },
    {
    name: "Kate Winslet"
    }
    ],
    _id: "5e973eef8af37634940e9a5b",
    title: "Titanic",
    director: "James Cameron",
    genre: "Romantic",
    imageURL: "https://www.google.com/url?sa=i&url=https%3A%2F%2Fencrypted-tbn0.gstatic.com%2Fimages%3Fq%3Dtbn%3AANd9GcQhYjUIu2o5v5u3rfJpCq5Cz0Q9WK--XdYxai_N2d0ImohPiIOp&psig=AOvVaw1SjoYtMGvlUsg-hW-iHO8c&ust=1588932208988000&source=images&cd=vfe&ved=0CA0QjhxqFwoTCMjSivG_oekCFQAAAAAdAAAAABAD",
    __v: 0
    }

```

我的 React 代码如下所示。

```
class MovieDetails extends Component 
    {
        constructor(props) {
          super(props);
          this.state = {
            movie: [],

            isLoaded: false,
          }

        }      
        componentWillMount() {
            let id = this.props.id;
            fetch(`http://localhost:5000/movie/details/${id}`)
            .then(res => {
              return res.json();})
            .then(movie => {
                this.setState({ movie });
            })

            .catch(console.log('error'));
        }        
        render() {
          return (
            <div className="container">
            <div className ="centre">
            <div className="col-xs-12"> 
            {this.state.movie.map((movie => (                  

                <div class="container" >
                    <div>
                        <h3>{movie.title}</h3>
                        <img src={movie.imageURL}  className="img-responsive"  height = "120" width ="120"/>
                        <h5 className="card-genre" >Genre : {movie.genre}</h5>
                        <h5 className="card-director">Directed by : {movie.director}</h5>

                    </div>
                </div>


            )
          ))}

          </div>
         </div>
         </div>
        );
      }
    }
    export default MovieDetails;
```

【问题讨论】:

标签: node.js json reactjs


【解决方案1】:

尝试在 div 中使用此代码

  {
    movie.actor.map(actor=>(
     <div>{actor.name}</div>
    ))
  }

您可以使用 li 标签而不是 div 或任何您想要的方式在列表中显示它

【讨论】:

  • 可能是 this.state.movi​​e.actor.map(),因为 @abhijeetjain 有一个 setState 函数正在更新电影值
  • @abhijeetjain 已经在迭代电影状态,从他提供的信息中,他成功获得了标题、类型、导演等的值。在这种情况下,我提供的代码应该可以工作
  • @abhijeetjain,将代码放在您打算访问导演姓名之后的行。
  • @Mohammed Fahim ,它有效,但不是您建议的方式。但是感谢您的帮助,您的建议给了我如何做的提示。
猜你喜欢
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
  • 2014-05-15
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多