【问题标题】:Why my state value is not changing in react even after changing its state? [duplicate]为什么我的状态值即使在改变状态后也没有改变? [复制]
【发布时间】:2021-11-25 04:33:28
【问题描述】:

我正在尝试通过我的 react 组件在 cloudinary 上上传文件,然后在成功上传文件时获取其 url。

这是我的组件:

export default function Write() {
  const [file, setFile] = useState(null)
  const [photo, setPhoto] = useState('')
  const postDetails = () => {
    const data = new FormData()
    data.append('file', file)
    data.append('upload_preset', 'mypresetname')
    data.append('cloud_name', 'mycloudname')
    console.log(photo)
    fetch('https://api.cloudinary.com/v1_1/mycloudname/image/upload', {
      method: 'POST',
      body: data,
    })
      .then((res) => res.json())
      .then((data) => setPhoto(data.url))
      .catch((err) => {
        console.log(err)
      })
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    postDetails()
  }

return (<form onSubmit={handleSubmit}>
              <input
                type='file'
                name='file'
                onChange={(e) => setFile(e.target.files[0])}
              /> 
    <button type='submit'> Publish </button></form>)}

当我尝试使用 .then((data) => console.log(data.url)) 而不是 .then((data) => setPhoto (data.url)) 我得到了正确的 url 但是当我在做 .then((data) => (setPhoto(data.url), console.log(photo)))强> 我得到照片的空字符串。为什么当我设置了 photo 的值时呢?

请帮忙 谢谢

【问题讨论】:

  • 你没有改变photo,它是常量。你改变了状态,所以下次你做useState时,你会看到它......

标签: javascript reactjs file-upload cloudinary


【解决方案1】:

setPhoto 不会立即运行,它必须重新运行函数才能看到效果。尝试将console.log(photo) 放在return 语句之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2023-03-13
    • 2018-12-29
    • 2023-02-16
    • 1970-01-01
    • 2019-07-22
    • 2021-05-24
    相关资源
    最近更新 更多