【发布时间】: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