javascript - 为什么我必须先克隆对象,然后才能在反应组件中访问它的属性?
问题描述
我从服务器获取了一些数据,并尝试在反应元素中使用,但我不断收到未定义的读取属性的类型错误。
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"]};
,一切正常,我现在可以访问该属性。为什么?谢谢你。
解决方案
推荐阅读
- java - Spring RabbitListener 在发送消息后调用方法
- python-3.x - PyParsing OnlyOnce
- java - 如何编写支持嵌套元组集合的java实体类?
- c# - 在 Blazor 中选择框绑定
- python - 使用 excel 表作为散景图的来源
- android - 修改ionic项目中的AndroidManifest.xml
- c# - Minesweeper:我想将我的地雷设置为二维数组。我怎样才能检查它?
- angular - 多个 Angular 组件的一个可重用动画?
- javascript - 如何获得第二个定义的单选按钮值?
- python - 从字符串列表中选择合适的选项