首页 > 解决方案 > ReactJS 错误:TypeError:this.state.data 未定义

问题描述

实际上学习 ReactJS,所以我制作了一个“应用程序”,它将与 Fetch 请求异步加载笑话并将它们加载到页面上。

反应代码

class App extends React.Component {
    constructor(props) {
       super(props);
       this.state = { 
           data : [],
        }
     }
    componentDidMount(){
     this.postdata()
    }

    postdata(){
        var initial_data = {'id': 1, 'model-name': 'Joke'}
        var self = this;
            fetch("\start-jokes\/", {
            body: JSON.stringify(initial_data),
            cache: 'no-cache', 
            credentials: 'same-origin', 
            headers: {
            'user-agent': 'Mozilla/4.0 MDN Example',
            'content-type': 'application/json'
            },
            method: 'POST',
            mode: 'cors', 
            redirect: 'follow',
            referrer: 'no-referrer',
            })
            .then(response => response.json()).then((json) => {
              self.setState({ data : json.data }) // which ever the key hold the data 
            })
    }

    render(){
       return( 
            <div>
            {this.state.data.length == 0 && 
               <div> No options available.</div>
            }
            {this.state.data.length > 0 && 
              <div className="container" id="jokes">
                   {this.state.data.map(function(item,i){
                          return(
                                <div key={i} className="card col-md-7">
                                <div className="card-body">
                                {item}   // here you are getting object in item. Get the key from the object like item.name
                                </div>
                                </div>
                      )
                   })}
               </div>
            }
          </div>
         )
    }
}
// ========================================

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

但是,它会在控制台中记录此错误消息。

TypeError: this.state.data is undefined

this.state.data在中被引用两次renderdataconstructor.

可能的原因是它没有从构造函数中获取它,因此失败了。

更新

多亏了我尝试记录的建议console.log(json.data),并且正如预期的那样回来了,undefined但是我确信有数据正确发送回来,只是它作为一个返回Object并且可能需要不同的方式来访问数据。

控制台日志json响应返回此Object { status: "ok", jokes: Array[10], ref-id: 11 }

标签: reactjs

解决方案


看起来json.data你在这里分配:

.then(response => response.json()).then((json) => {
  self.setState({ data : json.data }) // which ever the key hold the data 
})

未定义。


推荐阅读