将获取api数据反应到组件 [英] React fetch api data to component
本文介绍了将获取api数据反应到组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从The Movie数据库API制作一个应用程序.我遇到一个小问题.我有两个组成部分.首先,我使用fetch,并为Card组件使用map()函数,在该组件中我想显示api中的数据.如何正确连接它们?
I am trying to make an application from The movie data base api. I came across a small problem. I have two components. In first I use fetch and I use the map() function for the Card component in which I would like to display data from the api. How to connect them correctly?
https://codesandbox.io/s/p3vxqqz53q
渲染列表的第一个组件:
First component for render list:
import React, { Component } from 'react';
import Card from "./Card";
class ListApp extends Component {
constructor(props){
super(props);
this.state = {
items: [],
isLoaded: false,
}
};
componentDidMount = () => {
fetch("https://api.themoviedb.org/3/movie/popular?api_key=xxxxxxxx&page=1")
.then(resp => resp.json())
.then(resp => {
this.setState({
isLoaded: true,
items: resp.results
})
console.log(this.state.items)
})};
render() {
var {isLoaded, items} = this.state;
return (
<div>
{items.map( () => ( <Card/> ) )};
</div>
);
}
}
export default ListApp;
第二部分卡:
import React from 'react';
const Card = (items) => {
return (
<div className="movie-container">
<img src="https://image.tmdb.org/t/p/w185/{items.poster_path}" alt="NO PHOTO" className="movie-container__img" />
<div className="movie-container__about">
<span className="movie-container__percent">{items.vote_average}</span>
<h2 className="movie-container__title">{items.original_title}</h2>
<p className="movie-container__date">{items.release_date}</p>
<p className="movie-container__text">{items.overview}</p>
<a href="https://www.themoviedb.org/movie/" className="movie-container__more">MORE</a>
</div>
</div>
)
}
export default Card;
推荐答案
您需要将 item
对象作为道具传递给Card组件,例如
You need to pass the item
object as a prop to the Card component like
{items.map(item => <Card key={item.id} item={item} /> )}
,然后从
const Card = (props) => {
const {item} = props;
...
}
这篇关于将获取api数据反应到组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文