【问题标题】:user id goes to database null React用户 id 进入数据库 null React
【发布时间】: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 })的值是什么

标签: node.js reactjs frontend


【解决方案1】:

我不是真正的初学者程序员,也不是 SE 专家,但这是一个非常菜鸟的错误。由于我使用 spring boot 作为 api,列名必须与 JavaScript 中的变量名匹配,并且由于上面有问题的用户 ID 与我在 springboot 中的列名不匹配,因此将其视为“新phone who dis?”,因此为 null。

我想分享一些东西,我希望有人有同样的感受,但它总是如此,毫无例外,在编程中,总是小事情会导致最大的错误,而且真的会让人筋疲力尽。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2013-07-08
    • 1970-01-01
    相关资源
    最近更新 更多