ComponentDidMount和Axios设置状态之前的组件渲染



好的,所以在呈现方法中,我将gifs状态传递给我的GifList组件,问题是当我试图通过道具在该组件中使用该数组时,它说它是未定义的。经过进一步审查,我可以看到应用程序状态中的gifs属性最初是作为空数组传递的,然后setState将其设置为生命周期挂钩,因为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>
);
}

只有在列表中包含一些项目后,才能渲染GifList

render() { 
return (
<div className={styles.app}>
<Header title={this.state.title}/>
{
this.state.gifs.length && 
<GifList gifList={this.state.gifs}/>
}
</div>
);
}

导出默认应用程序;

最新更新