【问题标题】:Unhandled Rejection (TypeError)未处理的拒绝 (TypeError)
【发布时间】:2021-08-02 17:45:36
【问题描述】:

当我尝试单击“添加到收藏夹”按钮时,会出现此错误。仅当用户未登录时才会发生这种情况(我的用户登录路线不起作用,因此我无法同时测试两者)

Unhandled Rejection (TypeError): Cannot read property '_id' of undefined

addIntoUser
src/components/Card.js:56
  53 | 
  54 | const addIntoUser = async (event)=>{
  55 |   event.preventDefault();
> 56 |   const id = user._id;
     | ^  57 |   const title = props.title;
  58 |   try {
  59 |     const { data: newFavorites } = await apiCalls.addFavorite({id:id,title:title});

显然,我假设这是因为我的数据库中没有用户,但我想知道这是否也是代码中的另一个错误

【问题讨论】:

  • 使用前检查值user
  • const id = user?._idconst id = user && user._id 添加检查

标签: reactjs


【解决方案1】:

由于您没有用户,我认为您的 user 变量是空的,对吗?错误说user = undefined 试着打个console.log(user)自己看看吧。

有了这段代码和你所说的,没有其他错误,因为你没有用户信息,所以你的用户没有被逻辑定义。

如果你真的需要用户变量的 id,请尝试在之前定义它:

const addIntoUser = async (event)=>{
    event.preventDefault();
    // if no user defined (due to the fact that user not log in)
    if(!user)
        user = {_id:-1} // put whatever value of _id you want
    const id = user._id;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 2023-04-06
    • 1970-01-01
    • 2021-01-06
    • 2017-11-20
    • 2018-12-09
    • 2021-10-14
    • 2020-11-16
    相关资源
    最近更新 更多