有些东西我无法弄清楚。 这是一个基本的基于React类的组件,可以从端点获取一些数据:
import React from 'react'; import ReactDOM from 'react-dom'; class Example extends React.Component { state = { info: {} }; componentDidMount() { fetch('https://api.spacexdata.com/v2/info') .then(response => response.json()) .then(data => { const info = data; this.setState(() => ({ info })); }); } render() { return ( <div> {/* the first h1 renders just fine */} <h1>{this.state.info.name}</h1> {/* the second throws an error: Cannot read property 'address' of undefined */} <h1>{this.state.info.headquarters.address}</h1> </div> ); } } ReactDOM.render(<Example />, document.getElementById('root'));为什么第二个h1标签给我未定义? 我检查反应开发工具中的状态,并且数据在那里...它实际上是一个对象,它内部有另一个对象...如果我将同一对象粘贴到它呈现的状态就好...
There is something that I just can't figure out. Here is a basic React class-based component fetching some data from an endpoint:
import React from 'react'; import ReactDOM from 'react-dom'; class Example extends React.Component { state = { info: {} }; componentDidMount() { fetch('https://api.spacexdata.com/v2/info') .then(response => response.json()) .then(data => { const info = data; this.setState(() => ({ info })); }); } render() { return ( <div> {/* the first h1 renders just fine */} <h1>{this.state.info.name}</h1> {/* the second throws an error: Cannot read property 'address' of undefined */} <h1>{this.state.info.headquarters.address}</h1> </div> ); } } ReactDOM.render(<Example />, document.getElementById('root'));Why is the second h1 tag giving me undefined??? I check the state in the react dev tools and the data is there... It is literally an object that has another object within it... If I copy paste that same object into the state it renders just fine...
最满意答案
问题在于承诺的异步性质,当你第一次渲染组件时你开始承诺,但是它需要一些时间来执行和解决,所以它还没有返回JSON。这意味着信息仍然是{}和当你试图呈现你的H1
<h1>{this.state.info.headquarters.address}</h1>
你会得到未定义的错误。 由于this.state.info.headquarters未定义,因此您无法访问this.state.info.headquarters直到承诺解决(请记住它们是异步)
用这个(或类似的)替换你的初始状态
state = { info: {headquarters:{address:'loading...'} };
你会没事的。
The problem is the async nature of the promises, when you first render the component you start the promise but it will take some time to execute and resolve, so it didn't return the JSON yet.This means that info still being {} and when you try to render your H1
<h1>{this.state.info.headquarters.address}</h1>
you will get the undefined error. Because this.state.info.headquarters is undefined so you cannot access .address until the promise resolves(remember they are async)
just replace your initial state with this one(or something similar)
state = { info: {headquarters:{address:'loading...'} };
and you will be fine.
更多推荐
发布评论