【发布时间】:2019-06-21 00:58:44
【问题描述】:
我是新手,我无法将数组作为道具传递
在这个函数中,我从 flickr api 请求数据以显示照片,我使用 setState 来 cats 来保存该数据数组
//this function will retrieve the CATS pictures
renderCats = () => {
//fetch data from flickr
axios
.get(
` https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&tags=cats&per_page=24&format=json&nojsoncallback=1`
)
.then(response => { //set the response so that pics will be equal to the data array containing cat photos from flickr
console.log(response)
this.setState({
cats: response.data.photos.photo,
loading: false //initialize a loading state to display a loading message
});
})
.catch(error => { //this catch method outputs a message to the console, should axios fail to retrieve data
console.log("Something went wrong, could not access data", error);
});
};
然后在 render() 中我尝试使用下面的代码 sn-p,其中 /cats 是我的导航链接,我尝试渲染一个名为 Cats 的组件,但同时我试图通过使用 data={this.state.cats} 的数据数组
<Route path="/cats" render={ <Cats data={this.state.cats} /> } />
这也是我在我的 App 组件顶部所拥有的,我在其中使用 super() this.state 表示猫:[],我认为我挣扎的原因是因为我在这两者之间搞混了。 state 和 this.setState,任何改进我的代码的有用提示将不胜感激
class App extends Component { //Class components need to extend React.Component, and class components require the render()
constructor() {
//state for data we want to display from flickr
super();
this.state = {
pics: [], //this array will hold the pictures that will render as soon as the page loads
cats: [],
loading: true
};
}
componentDidMount() {
this.performSearch(); //call performSearch function on the componentDidMount() life cycle
this.renderCats()
}
【问题讨论】:
标签: javascript reactjs react-router