首页 > 解决方案 > 为什么我必须先克隆对象,然后才能在反应组件中访问它的属性?

问题描述

我从服务器获取了一些数据,并尝试在反应元素中使用,但我不断收到未定义的读取属性的类型错误。

import  React, { useEffect, useState }  from 'react';
import httpService from 'services/httpService';
function PageHighlight() {
  const [highlightItem,sethighlightItem]=useState({});
    async function fetchHighlightItem() {
        const {data}=await httpService.get('/PageHighlights');
        sethighlightItem(data)
    }
    useEffect(()=>{ fetchHighlightItem() },[]);
    console.log(highlightItem.NYCity)
    const item={...highlightItem["NYCity"]};

的结果console.log(highlightItem.NYCity)已经表明它是一个有效的对象: console.log 的结果显示它是一个对象

但是当我试图将它分配给一个变量并访问它时:const item=highlightItem["NYCity"];它返回一个从未定义读取属性的类型错误。 错误发生

如果我将它克隆到变量:const item={...highlightItem["NYCity"]};,一切正常,我现在可以访问该属性。为什么?谢谢你。

标签: javascriptreactjsobjecttypeerrorclone

解决方案


推荐阅读