Fetch Data from json file in React.js

陌路散爱 提交于 2021-01-28 02:02:18

问题


I have a json file call data.json such as ( I use React.js):

[{"id": 1,"title": "Child Bride"}, 
{"id": 2, "title": "Last Time I Committed Suicide, The"}, 
{"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"}, 
{"id": 4, "title": "Youth Without Youth"}, 
{"id": 5, "title": "Happy Here and Now"}, 
{"id": 6, "title": "Wedding in Blood (Noces rouges, Les)"}, 
{"id": 7, "title": "Vampire in Venice (Nosferatu a Venezia) (Nosferatu in Venice)"}, 
{"id": 8, "title": "Monty Python's The Meaning of Life"}, 
{"id": 9, "title": "Awakening, The"}, 
{"id": 10, "title": "Trip, The"}]

Im my componentDidMount I have the below:

      fetch('./data/data.json')
.then((response) => response.json())
.then((findresponse)=>{
  console.log(findresponse.title)
  this.setState({
    data:findresponse.title,
  })
})

}

and in my render:

 <ul>

         <li>        {this.state.title}</li>;


    </ul>

I would like to list all the title from my json file,

Otherwise it says that .then((response) => response.json()) is an anonymous function . . .

How to fix this ? I'm a bit confused

many thanks


回答1:


Your response isn't an object with a title property, it's an array of objects, all of which have title properties.

this.setState({ data: findresponse });

and then in your render

<ul>
  {this.state.data.map((x, i) => <li key={i}>x.title</li>)}
</ul>



回答2:


You can use async/await. It requires fewer lines of code.

async getData(){
   const res = await fetch('./data/data.json');
   const data = await res.json();
   return this.setState({data});
}

In the componentDidMount() call the function i.e.

componentDidMount(){
   this.getData();
}

Finally, in your render, you map the array of data

render (){
   return {<ul>{this.state.data.map(item => <li>{item.title}</li>)} </ul>
)
}



回答3:


You get the array of objects, thus you need to store then whole object in your state and then from the state read all title properties.

Your fetch should look as follows:

fetch('./data/data.json')
.then((response) => response.json())
.then((findresponse)=> {
  this.setState({
    data:findresponse
  })
})

And then in your render you should have something as follows:

render(){
    return (
      <ul>{this.state.data.map(item => <li>{item.title}</li>)} </ul>
    )
}

That will give you all title properties from data object.



来源:https://stackoverflow.com/questions/50291822/fetch-data-from-json-file-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!