在React Return {}中获取数据

时间:2019-05-23 14:52:13

标签: reactjs redux components

我有一个react组件,我想通过从我在浏览器中测试的url中获取数据并返回json data来填充其状态。但是在我的代码中我什么都没得到,这是我的代码:

    fetch(`https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json`)
      .then(response => response.json())
    //.then(data => JSON.stringify(data))
      .then(data => this.setState({
      latitude: position.coords.latitude, // this ois ok 
      longitude: position.coords.longitude, /// this is ok 
      locations : data // here I get {}
    }));

问题在我的渲染函数中

const { location } = this.state.locations;
alert("1" +JSON.stringify( this.state.locations));
alert("2" + JSON.stringify( location));

第一个警报已填满正确的数据,但第二个警报返回未定义。

1 个答案:

答案 0 :(得分:1)

您似乎正在尝试从此回复中破坏getBackstackSize()

location

如您所见,它没有{ "posts": [ { "_id": "5b3f761e21d434001487ad99", "title": "Hello Word!", "content": "The world is green!", "__v": 0 }, { "_id": "5b3f76b521d434001487ad9a", "title": "Sed porttitor lectus nibh", "content": "Sed porttitor lectus nibh. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Pellentesque in ipsum id orci porta dapibus. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Pellentesque in ipsum id orci porta dapibus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui.", "__v": 0 } ] } 属性,因此解构的结果将是不确定的。您是否在寻找正确的终点?