Making REST calls from a react component

前端 未结 4 1804
醉酒成梦
醉酒成梦 2021-01-30 17:30

I am trying to make REST call from a react component and render the returned JSON data into the DOM

Here is my component

import React from \'react\';

ex         


        
4条回答
  •  时光取名叫无心
    2021-01-30 18:15

    There are a couple of errors in your code. The one that's probably tripping you up is the this.setState({items:result.json()})

    Fetch's .json() method returns a promise, so it will need to be dealt with as async.

    fetch(`http://jsonplaceholder.typicode.com/posts`)
    .then(result=>result.json())
    .then(items=>this.setState({items}))
    

    I don't know why .json() returns a promise (if anyone can shed light, I'm interested).

    For the render function, here you go...

      {this.state.items.map(item=>
    • {item.body}
    • )}

    Don't forget the unique key!

    For the other answer, there's no need to bind map.

    Here it is working...

    http://jsfiddle.net/weqm8q5w/6/

提交回复
热议问题