【问题标题】:TypeError: undefined is not an object (evaluating 'object['body']')TypeError:未定义不是对象(评估'object ['body']')
【发布时间】:2020-12-12 15:45:48
【问题描述】:

我从服务器获得了一个数组。 这是数组:

[{"body":"one"},{"body":"two"},{"body":"three"}]

在 Home2 组件中:

import React, { Component } from 'react';

class Home2 extends Component {
    constructor() {
        super()
        this.state={
            status:''
        }
    }
    componentDidMount(){
        let store = JSON.parse(localStorage.getItem('login'))
        var url = 'http://127.0.0.1:8000/myapi/allpost/?format=json'
        fetch(url,{
            method:'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Token '+store.token
            }
        })
        .then(res=>res.json().then(result=>{
            this.setState({status: result})
        }))
    }
    render() {
        var list = this.state.status
        var object = list[0]
        console.log(object['body'])// <-- what is the problem?
        return (
            <div>
                <h1>Hello</h1>
            </div>
        );
    }
}

export default Home2;

代码运行时显示TypeError: undefined is not an object (evalating 'object['body']')

问题出在哪里? 如何 console.log 'one' ?

【问题讨论】:

  • 当你 console.log(object) 它记录什么?如果它记录 {"body":"one"} 那么你可以调用 object.body。但我认为它会记录未定义
  • n.b: render 被称为之前 componentDidMount(参见:reactjs.org/docs/react-component.html#mounting

标签: javascript reactjs


【解决方案1】:

正如人们在 cmets 中指出的那样,最初的 render 是在 之前 componentDidMount 完成的,所以这就是您收到错误的原因

要克服这个问题,您可以return 一些default 值(即Loading... div)以防this.state.status 尚未收到回复:

render() {
    var list = this.state.status
    var object = list[0]
    if (!object) {
      return (
        <div>
          Loading...
        </div>
      )
    }
    console.log(object['body'])// <-- what is the problem?
    return (
        <div>
            <h1>Hello</h1>
        </div>
    );
}

我还发现这个有趣的答案解释了更多关于 initial renderReact's 生命周期的信息: https://stackoverflow.com/a/45343644/5745962

【讨论】:

    【解决方案2】:

    您的渲染方法在 componentDidMount 方法之前被调用。因此,在尝试访问他的属性之前,您需要检查您的对象是否存在。

    另外,您需要决定要在状态中设置什么样的值(它是字符串还是数组?从您的代码看来它应该是一个对象数组 )

    尝试这样做:

    import React, { Component } from 'react';
    
    class Home2 extends Component {
        constructor() {
            super()
            this.state={
                status:[]
            }
        }
        componentDidMount(){
            let store = JSON.parse(localStorage.getItem('login'))
            var url = 'http://127.0.0.1:8000/myapi/allpost/?format=json'
            fetch(url,{
                method:'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Token '+store.token
                }
            })
            .then(res=>res.json().then(result=>{
                this.setState({status: result})
            }))
        }
        render() {
            if(this.state.status.length){
            var list = this.state.status
            var object = list[0]
            console.log(object['body'])// <-- what is the problem?
            return (
                <div>
                    <h1>Hello</h1>
                </div>
            );
            }
            else {
              return null; //or return in here some kind of loader
            }
        }
    }
    
    export default Home2;
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 2021-12-01
      • 2019-11-16
      • 2020-02-09
      • 2019-12-07
      • 2022-01-01
      • 2019-01-20
      • 2014-06-13
      • 2021-07-24
      相关资源
      最近更新 更多