setState 可能没有被执行

setState not being executed maybe

我有一个组件可以在单击按钮时从 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 时,会出现一个空值的警告框。我单击确定关闭它,但它再次打开。必须再次按下确定按钮。所以警告框也会出现两次。任何帮助,将不胜感激。谢谢

response 是一个承诺。在代码的一部分中等待它不会将同一变量转换为解析值。您需要将 awaiting 的结果分配给一个变量,该变量 保存解析值,然后将其传递给 setState:

fetch("https://example.com/v2/sites/list/" + this.state.name, {
    method: 'GET',
})
    .then(response => async (response) => {
        const result = await response.json();
        this.setState({
            names: result.items,
            fetching: false,
            fetched: true
        })
        toast.success(<NotifySuccess />)
    })
    .catch(error => toast.error(<NotifyFailure />));

@CertainPeformance 完全正确,只是添加了一些更简洁的方法,以防您可以使 handleSubmit 成为异步函数。

async handleSubmit(event) {
...
try {
 const response = await fetch("https://example.com/v2/sites/list/" + 
    this.state.name, {
    method: 'GET',
 })
 const { items } = await response.json()
 this.setState({
     names: items,
     fetching: false,
     fetched: true
 })
 toast.success(<NotifySuccess />)
} catch (error) {
 toast.error(<NotifyFailure />)
};