【问题标题】:TypeError: Cannot read properties of undefined (reading '0') whilte trying to accessing an array of object dataTypeError:在尝试访问对象数据数组时无法读取未定义的属性(读取“0”)
【发布时间】:2023-03-20 20:23:01
【问题描述】:

当我尝试访问从数据库中提取的数据(receivedData 是一个对象)时,我收到 TypeError: Cannot read properties of undefined (reading '0') .我试过console.log我的receivedData,它确实有数据。这是我的social structure looks 的样子,它是我的receivedData object 的键之一。

const logoObj = {
    "telegram": telegramWIcon,
    "twitter": twitterWIcon,
    "website": linkWIcon,
    "whitepaper": fileWIcon
  }

{receivedData.social[0] !== null &&
   <div>
       { Object.entries(receivedData.social[0]).forEach((item) =>
           item[1] !== null ? <SocialMedia url={logoObj.item[0]} link={item[1]} /> : ""
       )}
   </div>
}

【问题讨论】:

  • 你确定你得到的错误不是因为receivedData.socialundefined吗?尝试添加receivedData.social &amp;&amp; receivedData.social[0] !== null ...
  • @Alexandr 是的,这是error
  • 哦!我明白了:您尝试获取对象logoObj 的字段item,但我没有看到对象中的字段。你的意思是logoObj[item[0]]?其余代码也提出了问题。起初,将forEach 替换为map 看起来是个好主意:第一个不返回任何内容。

标签: javascript reactjs


【解决方案1】:
const logoObj = {
  telegram: telegramWIcon,
  twitter: twitterWIcon,
  website: linkWIcon,
  whitepaper: fileWIcon,
};

{receivedData.social[0] !== null && (
  <div>
    {Object.entries(receivedData.social[0]).map(([type, link]) => {
      if (!link || !logoObj[type]) {
        returt null;
      }

      return <SocialMedia key={link} link={link} url={type} />;
    })}
  </div>
)}

【讨论】:

    【解决方案2】:

    logoObj 中没有 item 字段。您需要使用logoObj[item] 动态访问密钥。

    const logoObj = {
        "telegram": telegramWIcon,
        "twitter": twitterWIcon,
        "website": linkWIcon,
        "whitepaper": fileWIcon
      }
    
    {receivedData.social[0] !== null &&
       <div>
           { Object.entries(receivedData.social[0]).forEach((item) =>
               item[1] !== null ? <SocialMedia url={logoObj[item][0]} link={item[1]} /> : ""
           )}
       </div>
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多