【发布时间】:2021-05-20 12:38:24
【问题描述】:
我正在尝试在 useEffect() 内的 Promise 函数内设置钩子的值,并能够将返回的承诺值存储在 fruit 钩子中,以便我可以在 @987654324 的返回函数中访问它@
这是我迄今为止尝试过的:
const MyComponent = () => {
const [fruit, setFruit] = useState('')
useEffect(() => {
// my promise function that returns a string (a random fruit)
promiseFunction()
.then(value => setFruit(value))
}, [])
return <div>fruit ? fruit : Loading...</div>
}
到目前为止,我已经尝试了很多方法,但都没有奏效。
useEffect(() => {
promiseFunction()
.then(value => setFruit(() => value))
}, [])
useEffect(() => {
promiseFunction()
.then(value => setFruit((value) => { fruit = value }))
}, [])
毕竟,钩子的返回值还是空的。
没有错误消息或任何东西,我尝试使用另一个 useEffect 进行调试,它仍然在控制台中返回一个。
如何获取promise函数的返回值并将其存储在fruit变量中?
【问题讨论】:
-
您是否确认(使用
console.log消息或调试)该承诺实际上通过非空value实现? -
<div>fruit ? fruit : Loading...</div>必须是<div>{fruit ? fruit : 'Loading...'}</div>但否则第一个 sn-p 应该可以正常工作。不要忘记在你的 Promise 中添加一个.catch()错误处理程序。 -
@Bergi 是的,它确实返回了一个值
-
那么应该没有问题。请提供minimal reproducible example
标签: javascript reactjs promise react-hooks