And*_*Zaw 2 javascript reactjs
我已经简化了大部分代码,因为问题在于 Promise 和 async/await 部分。
我希望这个组件从我的 API 获取数据并从中创建一个图。如果 API 仍在检索,我希望它显示加载图标。
class Data extends Component {
state = {};
componentDidMount() {
this.setState({ data: this.getData() });
}
async getData() {
try {
const response = await axios.get('/api/data');
return response.data;
} catch (err) {
return [];
}
}
renderLoading() {
return <Loading/>; // this represents a loading icon
}
renderPlot(data) {
return <Plot data={data}/>; // this represents the plot that needs the data
}
render() {
return {this.state.data
? this.renderLoading()
: this.renderPlot(this.state.data)};
}
}
Run Code Online (Sandbox Code Playgroud)
目前,它所做的是 check this.state.data,看到它是未定义的,并且只是永远显示加载图标而无需再次检查它。一旦承诺完成,我如何让它重新检查?需要注意的一个问题是 renderPlot 需要完成数据,如果我在 Promise 仍处于挂起状态时调用 renderPlot,它不会正确处理它。
而不是调用的setState之前的数据已经准备好,通话this.getData()中componentDidMount,然后调用setState一次响应数据已准备就绪。React 将自动重新渲染具有状态更改的组件。
class Data extends Component {
state = {}
componentDidMount() {
this.getData()
}
getData() {
axios
.get('/api/data')
.then(({ data }) => {
this.setState({ data })
})
.catch(err => {
this.setState({ error: err.message })
})
}
render() {
return this.state.data
? <Plot data={this.state.data} />
: this.state.error
? <div>{this.state.error}</div>
: <Loading />
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
977 次 |
| 最近记录: |