简体   繁体   English

反应本机提取和componentDidMount

[英]React native fetch and componentDidMount

I'm trying to fetch some data and display on render method: 我正在尝试获取一些数据并在render方法上显示:

constructor(props) {
   super(props);

   this.state = {
     job: {}
   }
}

componentDidMount() {
   fetch(API_URL).then((res) => res.json()).then((res) => this.setState({ job: res.job }));
}

render() {
   return (<Text>{this.state.job.name}</Text>)
}

But when the screen is loaded and I try to access the job name occurs an exception: 但是,当加载屏幕并尝试访问作业名称时,会发生异常:

undefined is not an object 未定义不是对象

How can I fetch data from an API and render properly ? 如何从API获取数据并正确呈现? Thanks. 谢谢。

Since fetch is asynchronous, your view will try to render and is looking for name which does not exist yet. 由于fetch是异步的,因此您的视图将尝试呈现,并且正在寻找尚不存在的name You can have a Loading... state for this if you wish in your render method, like so - 如果您愿意,可以在render方法中为此设置“ Loading...状态-

render() {
  if (!this.state.job.name) {
    return (
      <div>Loading...</div>
    );
  }

  return (<Text>{this.state.job.name}</Text>);
}

fetch is asynchronous, and the first render will occur before the state is set. fetch是异步的,并且第一次render将在设置状态之前发生。 Until then, this.state.job.name is undefined. 在此之前, this.state.job.name是未定义的。

However, I think your error might actually come from the way you're handling the response, and that you're setting this.state.job to undefined. 但是,我认为您的错误实际上可能来自处理响应的方式,并且您将this.state.job设置为undefined。 Note that the code below is asynchronous but produces no error, even before this.state.job.name is defined. 请注意,以下代码是异步的,但即使在定义this.state.job.name之前,也不会产生任何错误。

You need to make sure that you're handling your response correctly and setting this.state.job to an object, otherwise you will get an exception when you try and access the name property. 您需要确保正确处理响应并将this.state.job设置为一个对象,否则当您尝试访问name属性时,您将获得异常。

 class Test extends React.Component { constructor(props) { super(props); this.state = { job: {} }; } componentDidMount() { setTimeout(() => this.setState({ job: { name: "job" } }), 1000); } render() { return (<p>{this.state.job.name}</p>); } } ReactDOM.render(<Test/> , document.getElementById("app")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM