简体   繁体   中英

Getting Object: “undefined” on React

I am a newbie in react JS and I am trying to pull data from a url in Json format. I did the following but I keep on getting a feeback at the console as

Rovers: undefined.

How do I go about it when am supposed to get something like

Rovers:[object, object, object]

class App extends React.Component {
 constructor(props){
   super(props);
   this.state={rovers:[]};
 }
componentWillMount(){
  api.getRovers().then((response) =>{
   this.setState({
     rovers: response.rovers
   });
 });
}
render() {
  console.log("Rovers: ", this.state.rovers);
}

and this is where am calling the json link

var api={
  getRovers(){
   var url='https://jsonplaceholder.typicode.com/posts/1';
   return fetch(url).then((response)=> response.json());
 }
};
module.exports=api;

The endpoint replies with object that does not include rovers . However, it includes : id , userId , title and body


在此处输入图片说明


That's why response.rovers is undefined . Then this.state.rovers is the same

So , you might mean body instead of rovers , in this case , replace:

componentWillMount(){
  api.getRovers().then((response) =>{
   this.setState({
     rovers: response.rovers
   });
 });
}

By :

componentWillMount(){
  api.getRovers().then((response) =>{
   this.setState({
     rovers: response.body.split('\n')
   });
 });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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