簡體   English   中英

“TypeError:無法將未定義或 null 轉換為對象”渲染嵌套的 JSON

[英]“TypeError: Cannot convert undefined or null to object” rendering a nested JSON

我正在嘗試在反應中渲染嵌套的 JSON,但當我嘗試渲染嵌套部分時收到錯誤“TypeError:無法將未定義或 null 轉換為對象”。 當通過 componentDidMount() 方法存儲在組件的 state 中時,這些部分將轉換為對象,因此我嘗試使用 Object.keys() ZC1C425268E68385D1AB50741C 例如,在下一個 JSON 中:

{
    "gear": 14,
    "valid": 1,
    "meteo": {
        "wind_direction": 152,
        "wind_velocity": 10.1
    },
}

當我嘗試使用 Object.keys() function 渲染它時,像這樣:

const haul = this.state.haul
{Object.keys(haul.meteo).map( key => {
     return(<p>Sea state: {haul.meteo[key]} </p>)
})} 

錯誤是在 Object.keys() 行中拋出的,我不明白為什么。

完整的組件是這樣的:

class ComponentsHaul extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            haul: []
         };
        this.apiHaul = "http://myapi";
    }
    componentDidMount() {
        fetch(this.apiHaul)
            .then(response => {
                return response.json();
            })
            .then(haul => {
                this.setState(() => {
                    return {
                        haul
                    };
                });
            });
    }
    render() {
        const haul = this.state.haul
        return ( 
            <Fragment>
            <p>Gear: {haul.gear}</p>
            {Object.keys(haul.meteo).map( key => {
                return(<p>Sea state: {haul.meteo[key]} </p>)
                })}    
            </Fragment>
        );
    }
}

haul最初是一個數組,沒有meteo ,所以Object.keys(haul.meteo)失敗。 然后,您稍后將類型(禁止)更改為 object,保持類型一致。

 const state = { haul: [] }; console.log(Object.keys(state.haul.meteo));

如果您更改您的初始 state 以提供一個空的meteo object,這應該適用於您在獲取數據時的初始和后續渲染。

this.state = {
  haul: {
    meteo: {},
  },
}

 const state = { haul: { meteo: {} } }; console.log(Object.keys(state.haul.meteo));

這是因為當您第一次渲染組件時,您的 state 是空的。

只需添加一個條件:

{ hulu.meteo.length > 0 && Object.keys(haul.meteo).map( key => {
    return(<p>Sea state: {haul.meteo[key]} </p>)
})}  

您應該首先檢查您的haul state 是否有meteo 當組件渲染時,您的獲取數據還沒有准備好。 因此,使用尚不存在的屬性是不安全的。

render() {
  const haul = this.state.haul;

  if(!haul.meteo) {
    return <p>Loading...</p>
  }

  return (
    <Fragment>
      <p>Gear: {haul.gear}</p>
        {Object.keys(haul.meteo).map((key) => {
          return <p key={key}>Sea state: {haul.meteo[key]} </p>;
        })}
    </Fragment>
  );
}

而且,當然,不要忘記在渲染 React 子數組時添加key prop。

這個問題在第一次渲染時出現。

看,運輸是 state 包含空數組 []。 當它第一次渲染時,React 嘗試在線訪問meteo

Object.keys(haul.meteo)

但是haul沒有未定義的名為meteo的屬性。 因此,React 讀起來像

Object.keys(undefined)

你得到這個錯誤。 componentDidMount在第一次渲染后運行)

解決方案:首先檢查meteo的存在,像這樣。

{
haul.meteo ? Object.keys(haul.meteo).map( key => {
                return(<p>Sea state: {haul.meteo[key]} </p>)
                })} : []
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM