Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 处于React状态的对象中的对象返回undefined_Reactjs_Fetch - Fatal编程技术网

Reactjs 处于React状态的对象中的对象返回undefined

Reactjs 处于React状态的对象中的对象返回undefined,reactjs,fetch,Reactjs,Fetch,有些事我就是搞不懂。下面是一个基本的基于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') .th

有些事我就是搞不懂。下面是一个基本的基于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'));
从“React”导入React;
从“react dom”导入react dom;
类示例扩展了React.Component{
state={info:{};
componentDidMount(){
取('https://api.spacexdata.com/v2/info')
.then(response=>response.json())
。然后(数据=>{
const info=数据;
this.setState(()=>({info}));
});
}
render(){
返回(
{/*第一个h1渲染得很好*/}
{this.state.info.name}
{/*第二个抛出错误:无法读取未定义的*/}的属性“address”
{this.state.info.headers.address}
);
}
}
ReactDOM.render(,document.getElementById('root'));

为什么第二个h1标签给我的是未定义的???我在react dev工具中检查状态,数据就在那里。。。它实际上是一个物体,里面有另一个物体。。。如果我将同一个对象复制粘贴到它呈现的状态,那么问题在于承诺的异步性质,当您第一次呈现组件时,您启动了承诺,但执行和解析需要一些时间,因此它还没有返回JSON。这意味着信息仍然是
{}
当您尝试渲染H1时

{this.state.info.headermission.address}

您将得到未定义的错误。因为
this.state.info.headquarters
未定义,所以在承诺解决之前,您无法访问.address(记住它们是异步的)

用这个(或类似的东西)替换你的初始状态

state={info:{总部:{地址:'loading…'};


你肯定有
info.name
吗?
name
的值是多少?@Tomasz是的……只要将url复制粘贴到浏览器中,你就会看到……它就在对象上。似乎只有其中的嵌套对象会抛出错误……那么为什么第一个H1会呈现?只有在尝试呈现第二个H1时才会呈现它抛出未定义的错误…因为在第一个错误中,你有对象信息。当你尝试访问名称时,它返回未定义的。没关系。只有当你尝试下一个级别时,你才会得到错误。因为你尝试访问未定义的属性,这会导致错误。明白了。我确实做到了{this.state.info.headquareters?this.state.info.headquarters.address:'正在加载…'}