【发布时间】:2021-07-26 08:55:19
【问题描述】:
我有一个组件可以通过单击按钮从 API 中获取项目列表。名称状态变量来自输入框。我的 handleSubmit 方法的代码是:
handleSubmit(event) {
event.preventDefault()
this.setState({
fetching: true
})
fetch("https://example.com/v2/sites/list/"+this.state.name, {
method: 'GET',
})
.then(response => async(response) => {
await response.json()
this.setState({
names: response.json()["items"],
fetching: false,
fetched: true
})
toast.success(<NotifySuccess />)
})
.catch(error => toast.error(<NotifyFailure />));
}
在将获取的状态值设置为 true 时,在我的渲染方法中,我试图通过门户渲染一个包含名称值的警报框,但似乎 setState 没有按预期工作。没有出现警告框,并且在通过 React 开发人员工具检查组件时,获取的状态值未更新为 true。为什么不更新?另外,当我使用开发人员工具将其设置为 true 时,会出现一个带有空值的警报框。我单击确定将其关闭,但它再次打开。必须再次按确定按钮。所以警告框也会出现两次。任何帮助,将不胜感激。谢谢。
【问题讨论】:
标签: reactjs async-await setstate