好了,所以在render方法中,我将gifs状态传递给了我的GifList组件,问题是当我尝试通过该组件的说法使用未定义的数组,并进一步检查后,可以看到该应用程序状态中的gifs属性在setState将其设置为生命周期挂钩中我的Axios调用的返回值之前,由于Axios是异步的,所以它最初作为空数组传递。我该如何解决这个问题?
import React, { Component } from 'react';
import axios from "axios";
import styles from './App.css';
import Header from './Components/Header/Header';
import GifList from './Components/GifList/GifList';
class App extends Component {
state = {
title: "Giphy Search App",
gifs: []
}
componentDidMount() {
axios.get("http://api.giphy.com/v1/gifs/search? q=funny+cat&limit=20&api_key=ms344CewNH5NEbybHwQifMZImoQfEQ38")
.then((res) => {
const arr = res.data.data;
this.setState({ gifs: arr });
});
}
render() {
return (
<div className={styles.app}>
<Header title={this.state.title}/>
<GifList gifList={this.state.gifs}/>
</div>
);
}
}
export default App;
最佳答案
您可以等待渲染GifList
,直到您的gifs
数组中包含某些内容为止。这基本上是jsx的内联if语句。
render() {
return (
<div className={styles.app}>
<Header title={this.state.title}/>
{this.state.gifs.length > 0 && <GifList gifList={this.state.gifs}/>}
</div>
);
}