已写的代码如下:
function Homepage() {
async componentDidMount() {
const curCity =
await
getCurrentCity()
this.setState({
curCityName: curCity.label
})
}
vscode里报错如下:
chrome浏览器报错如下:
代码里如果写了await时,需要在上一级写上async,目前已写上了async,请问为何仍报错?问题出在哪里?
只有类组件里才能用生命周期函数。函数式组件里就不应该用componentDidMount。当然你可以将componentDidMount视作一个普通的函数,你可以加个 async function componentDidMount() {};但这样显得太傻了
await必须作用于一个需要等待的对象,比如多线程对象或者异步对象,你不要把一个普通函数前面放上await,这本来就是顺序执行的不需要等待
你在 生命周期 前面 加 async 肯定不行