【发布时间】:2019-08-01 16:54:48
【问题描述】:
我是 react 和 javascript 的新手,在尝试从 Promise 中检索值以便将其用于操作时遇到了麻烦。我做了一些研究,看到了很多可以返回控制台日志或运行函数的 Promise 教程。但是我还没有看到一个可以让我保存到 const/var 以便我可以用于其他操作(如 setstate)的方法。
我尝试了不同的方法来解决来自异步函数的承诺,因此我可以执行 setstate,但它们都失败了,我已将范围缩小到 3 种方法,我尝试过哪个控制台记录正确的信息,但是当我setstate 失败。
这是我的反应组件的示例
state = {
user: {}
}
getCurrentUser = async () => {
// to save the user details if they are logged in
const jwt = localStorage.getItem('token')
return jwtDecode(jwt)
}
componentDidMount() {
// method 1
// returns a promise instead of a value so setstate fails
let user = this.getCurrentUser()
console.log(user)
this.setState({user: user})
console.log(this.state)
// method 2
// trying to resolve a promise and return a value so I save to a variable and then setstate
user = this.getCurrentUser()
user = user.then((value) => {
//console log prints out exactly what I need
console.log(value)
return value
})
console.log(user)
this.setState({user: user})
console.log(this.state)
// method 3
// trying to do setstate inside the promise also fails
user = this.getCurrentUser()
user.then((value) => {
this.setState({user: value})
})
console.log(this.state)
}
感谢您提供任何关于如何解决此问题的提示,或者如果我对异步或承诺的概念有误解。
【问题讨论】:
-
在你的
getCurrentUser函数中你没有等待任何东西?
标签: javascript reactjs