【发布时间】:2025-12-19 09:10:15
【问题描述】:
我试图在 componentDidMount 上获取一些数据来设置反应状态。
我在 componentdidMount 上使用异步等待,获取一些数据,等待它,当它完成后将我的状态设置为数据。
我在本文中遵循完全相同的模式:https://medium.com/front-end-weekly/async-await-with-react-lifecycle-methods-802e7760d802
这是我的 componentDidMount 方法:
const url = "http://localhost:3001";
const opts = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query })
};
await fetch(url, opts)
.then(res => res.json())
.then(data => this.setState({
photographers: data
}))
.catch(console.error);
}
然后在我的渲染方法中,我尝试使用状态值.. 但它未定义:
render() {
console.log('here:', this.state)
return (
<React.Fragment>
<div className="red ba">Hella!</div>
<List photographers={this.state.photographers}/>
</React.Fragment>
)
}
我之前用过 asunc await 很多次,我知道它是如何工作的,但是为什么这不起作用?谢谢!
【问题讨论】:
-
您不需要在
componentDidMount的示例代码中使用await,因为您从不在方法本身中使用结果。在组件实际安装到 DOM 后,componentDidMount也会触发。所以,第一个render已经发生了。而第一次渲染显然会在获取任何内容之前看到初始状态。
标签: reactjs asynchronous