【问题标题】:useState keeps getting cleared while handling promisesuseState 在处理承诺时不断被清除
【发布时间】:2021-03-25 09:56:59
【问题描述】:

我的 react 应用程序的 useState 不断重置为默认值。当我的承诺功能完成时它会重置。我在控制台记录时观察到了这一点。 值 imageUpload state 是用来设置然后用 axios 发送的,但是,当它移动到下一个 promise 时,状态被重置。它只发生在图像上传

这里是useState函数的sn-p:

const [values, setValues] = useState({
name: "",
caption: "",
...
imageUpload: "",
})

这是给出问题的主要代码:

const clickSumbit = (event) => {
setValues({...values, error: '', loading: true})

event.preventDefault();
onFileUpload().then( data => {
  setValues({...values, imageUpload: `https://${storageAccountName}.blob.core.windows.net/all/${event.target.files[0].name}`})

  console.log("imageUpload", imageUpload);
}).then( () => {
  axios.post('/.netlify/functions/addData', values)
  .then(data => {
    console.log("Values posted!")
    setValues({
      ...values,
      name: '',
      description: '',
      photo: '',
      error: "",
      loading: false,
      createdProduct: name
    })
  })
  .catch(error => setValues({...values, error: error})
)
  
})



};

这里是onFileupload函数的sn-p

const onFileUpload = async () => {

const blobsInContainer = await uploadFileToBlob(fileSelected);
return blobInContainer
};

编写此代码的目的是,在成功完成 onFileUpload 函数得到响应之前,axios post 请求将成功。

当我尝试将 OnSumbit() 设为异步函数时,情况更糟。我是 async 和 await 的新手,这正常吗?

【问题讨论】:

  • TL/DR,但“价值。它会在我的承诺功能完成时重置。”听起来像是一个常见问题:values 可能在调用 setValues 时包含过时的信息。像这样更新你的状态:setValues((values) => ({ ...values, etc }))

标签: reactjs asynchronous promise use-state


【解决方案1】:

useState 是一个异步操作,因此您的状态可能不会立即更新。我建议提供一个 useEffect 监听值的变化并调用下一个请求。另外,如果你的新状态依赖于旧状态,你应该传递这样一个函数:

onst clickSumbit = (event) => {
  setValues(prevState => { return {...prevState, error: '', loading: true}})
  event.preventDefault();
  onFileUpload().then( data => {
    setValues(prevState => { return {...prevState, imageUpload: `https://${storageAccountName}.blob.core.windows.net/all/${event.target.files[0].name}`})
  }})
};
useEffect(() => {
  // only call request when imageUpload is available amd first time it receives image 
  if(values.imageUpload && values.loading) {
    axios.post('/.netlify/functions/addData', values)
     .then(data => {
     setValues( prevState => { return {
      ...prevState,
      name: '',
      description: '',
      photo: '',
      error: "",
      loading: false,
      createdProduct: name
    }})
   })
   .catch(error => setValues({...values, error: error})
 }
}, [values])

记住:useEffect 将在每次值更改时触发。因此,您必须小心避免调用不必要的请求,只使用 imageUpload 的加载状态(或一个状态专用来了解 imageUpload 操作的状态)

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 2021-09-15
    • 2018-07-04
    • 2022-01-22
    • 1970-01-01
    • 2020-04-11
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多