通过抓取获取请求并做出反应

时间:2017-11-21 20:57:15

标签: javascript json reactjs fetch

这可能是一个非常愚蠢的问题,但我无法在网上找到任何解决方案,请不要打击我。我设置了一个create-react-app,想要在表格中显示一些数据。

这是我的JSON:

[ {
  "unitid" : 29,
  "createddate" : 1510324778000,
  "latitude" : 49.402008056640625,
  "longitude" : 11.901968002319336,
  "senderid" : 6,
  "signalstrength" : 37
}, {
  "unitid" : 34,
  "createddate" : 1510563384000,
  "latitude" : 49.22679901123047,
  "longitude" : 12.845210075378418,
  "senderid" : 8,
  "signalstrength" : 0
},......

我的表需要一个包含所有属性的JSON数组才能正确显示每一列。

这是我尝试从我的端点获取数据的代码:

class App extends Component {
constructor(props){
    super(props);

    this.state = {
        vehicleList: [],
    };
}

componentDidMount(){
    fetch('endpoint-link', {mode: 'no-cors', method: 'get'})
        .then(response => response.json())
        .then(result => {
            this.setState({vehicleList: result.vehicleList})
            console.log(result)
        })

        .catch(error => {
            this.setState({isLoaded: true, error})
            console.log(error)
        });
}

render() {
    const {vehicleList} = this.state;
    console.log(vehicleList);.......

当我在Chrome中打开Devtools时,转到“网络”我可以看到端点已知并且找到了数据,但是某种方式fetch方法没有将JSON加载到Array中。

2 个答案:

答案 0 :(得分:0)

您的JSON没有vehicleList属性。它只有一系列的车辆。所以你需要把它放在你的状态:

this.setState({vehicleList: result})

答案 1 :(得分:0)

问题是这个 - > ...{mode="no-cors"...} 请参阅此帖子以修复它:Handle response - SyntaxError: Unexpected end of input