【问题标题】:"TypeError: Cannot convert undefined or null to object" rendering a nested JSON“TypeError:无法将未定义或 null 转换为对象”呈现嵌套 JSON
【发布时间】:2020-06-12 17:58:42
【问题描述】:

我正在尝试在 react 中渲染嵌套的 JSON,但是当我尝试渲染嵌套部分时收到错误“TypeError:无法将未定义或 null 转换为对象”。当通过 componentDidMount() 方法存储在组件的状态中时,这些部分将转换为对象,因此我正在尝试使用 Object.keys() 函数。 例如,在下一个 JSON 中:

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

当我尝试使用 Object.keys() 函数渲染它时,如下所示:

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) 失败。

标签: javascript json reactjs


【解决方案1】:

haul 最初是一个数组,没有meteo,所以Object.keys(haul.meteo) 失败。然后,您稍后将类型(a no-no)更改为对象,保持类型一致。

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

如果您更改初始状态以提供一个空的 meteo 对象,这应该适用于获取数据时的初始和后续渲染。

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

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

【讨论】:

    【解决方案2】:

    这是因为当你第一次渲染组件时,你的状态是空的。

    只需添加一个条件:

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

    【讨论】:

      【解决方案3】:

      您应该首先检查您的haul 状态是否有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 属性。

      【讨论】:

        【解决方案4】:

        此问题在首次渲染时出现。

        看,haul 是包含空数组 [] 的状态。当它第一次渲染时,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>)
                        })} : []
        }
        

        【讨论】:

          猜你喜欢
          • 2021-01-23
          • 2023-02-21
          • 1970-01-01
          • 2021-12-12
          • 2020-08-04
          • 2013-08-14
          • 2021-12-07
          • 2022-10-24
          • 2023-01-20
          相关资源
          最近更新 更多