【发布时间】:2021-10-19 05:19:25
【问题描述】:
我正在尝试在 React 中创建简单的功能,当用户购买商品时,他们登录的用户名将被注入数据库。到目前为止,我已经完成了它并且它可以工作,但是对不同的函数执行相同的操作,用户 ID 进入 NUll。
//fetch user information from form
const bookToBePurchased = {
userFirstName: this.state.userFirstName,
userLastName: this.state.userLastName,
userAddress: this.state.userAddress,
userId: jwt_decode(localStorage.getItem("token"), { body: true })["username"], // doesnt work, need to discuss
bookListingId: this.props.bookListingId,
transactionStatus: this.props.paymentStatus,
paymentId: this.props.paymentId
}
我也尝试了以下
componentDidMount(){
this.setState({userID : jwt_decode(localStorage.getItem("token"), { body: true })["username"]})
}
//post user input into transactions API
onSubmit(e){
e.preventDefault();
//fetch user information from form
const bookToBePurchased = {
userFirstName: this.state.userFirstName,
userLastName: this.state.userLastName,
userAddress: this.state.userAddress,
userId: this.state.userID, // doesnt work, need to discuss
bookListingId: this.props.bookListingId,
transactionStatus: this.props.paymentStatus,
paymentId: this.props.paymentId
}
如您所见,在 userId 中,当我 console.log jwt_decode 时,会出现正确的 userID,当我设置状态然后显示状态时,它仍然有效,但是当我放置 userID 的值时,它会继续在空。不知道为什么。我尝试了很多解决方案,在 2 天的时间里,仍然没有运气。在另一个函数中,我尝试了两种方法,这两种方法都适用于另一个函数,但不是这个。
【问题讨论】:
-
您的
jwt_decode有可能返回空值。尝试先打印出来。 -
或者你可能需要在 jwt_decode 之前等待
-
@ShubhamVerma 我确实将它打印在整个页面上,它可以工作。
-
@Mahi 你能详细说明一下吗?
-
请告诉我们
localStorage.getItem("token")和jwt_decode(localStorage.getItem("token"), { body: true })的值是什么