gpt4 book ai didi

javascript - React Native 不要在 componentDidMount 中使用 setState (react/no-did-mount-set-state)

转载 作者:行者123 更新时间:2023-11-28 03:07:38 26 4
gpt4 key购买 nike

使用 React Native 和 API 我遇到过这样的问题:不要在 componentDidMount 中使用 setState (react/no-did-mount-set-state)谁知道背后的原因?

这是我的代码首页.js

  state = {
users: []
}

async componentDidMount() {
const users = await ajax.fetchUsers();
this.setState({users});
}

这里是FetchData.js

async fetchUsers() {
try {
let response = await fetch(URI + '/users');
let responseJsonData = await response.json();
return responseJsonData;
}
catch(e) {
console.log(e)
}
}

最佳答案

我的猜测是,您收到该错误是因为相关工具没有意识到您已将 async 添加到 componentDidMount,因此它认为您是同步componentDidMount中设置状态。

你不应该这样做。 componentDidMount 未在 React.Component 中定义为 async 方法。当您扩展的类未以这种方式定义方法时,请勿将方法设为异步。如果您进行 componentDidMount async,则没有任何东西可以处理您将返回的 promise 。

相反,使用包装器async函数(并处理错误!!):

componentDidMount() {
(async() => {
try {
const users = await ajax.fetchUsers();
this.setState({users});
} catch (e) {
// ...handle/report error here...
}
})();
}

或者甚至将其分解为自己的方法:

componentDidMount() {
this.loadInitialUsers(); // Note: No `await`
}

async loadInitialUsers() {
// Important: This must not throw any errors, because nothing handles
// the promise rejection that would create
try {
const users = await ajax.fetchUsers();
this.setState({users});
} catch (e) {
// ...handle/report error here...
}
}

关于javascript - React Native 不要在 componentDidMount 中使用 setState (react/no-did-mount-set-state),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60467541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com