无法读取未定义的属性“材料”。用嵌套对象反应useState

时间:2019-09-14 20:17:49

标签: javascript json reactjs api react-hooks

我正在尝试将此API调用的结果存储到我的状态中。当我尝试在JSX中将任何对象称为“数据”状态时,例如:data [“ Rank A:Real-Time Performance”]。Materials,我得到未定义的错误。如果状态变量不是嵌套对象,则可以正常工作。有人可以指出我正确的方向吗?我做错了什么,还是这种不好的做法?谢谢

这是API响应的示例

{
"Meta Data": {
    "Information": "US Sector Performance (realtime & historical)",
    "Last Refreshed": "04:20 PM ET 09/13/2019"
},
"Rank A: Real-Time Performance": {
    "Materials": "1.14%",
    "Financials": "0.84%",
    "Energy": "0.80%",
    "Industrials": "0.52%",
    "Communication Services": "-0.05%",
    "Health Care": "-0.07%",
    "Consumer Discretionary": "-0.19%",
    "Utilities": "-0.57%",
    "Information Technology": "-0.67%",
    "Consumer Staples": "-0.75%",
    "Real Estate": "-1.27%"
},

这是React代码:

import {useState, useEffect} from 'react';


const SectorData = () => {
    let [data, setData] = useState({});

    async function fetchData() {
        try {
            const url = "https://www.alphavantage.co/query?function=SECTOR&apikey=VZI9OTBHE0X9Y1JD";
            const response = await fetch(url);
            const json = await response.json();
            // This console log prints perfectly
            console.log("json = " + json["Rank A: Real-Time Performance"].Materials)
            setData(json)         
        } catch (e) {
            console.error(e);
        }
    };
    useEffect(() => {  
        fetchData();
      }, [])

    return(
        <>
            {data["Rank A: Real-Time Performance"].Materials}
        </>
        
    )
}

export default SectorData

我通过使用next.js getInitialProps函数找到了解决方法。

但是我怎么只用React来实现这样的onload api调用呢?

1 个答案:

答案 0 :(得分:2)

data最初是一个空对象。之所以得到undefined,是因为您试图访问该空对象的不存在的属性。因此,添加一个条件来检查您是否没有数据(或没有键的对象)。例如:

if (!Object.keys(data).length) return <div>No data</div>;

return (
  <>
    {data["Rank A: Real-Time Performance"].Materials}
  </>  
)