因此,我一直将以下代码放入我的React JS组件中,而我基本上是试图将两个API调用都置于一种称为vehicles的状态,但是以下代码却出现了错误:

componentWillMount() {

    // Make a request for vehicle data

    axios.all([
      axios.get('/api/seat/models'),
      axios.get('/api/volkswagen/models')
    ])
    .then(axios.spread(function (seat, volkswagen) {
      this.setState({ vehicles: seat.data + volkswagen.data })
    }))
    //.then(response => this.setState({ vehicles: response.data }))
    .catch(error => console.log(error));
  }

现在,我猜我无法像this.setState({ vehicles: seat.data + volkswagen.data })一样添加两个数据源,但是还可以怎么做?我只希望将来自该API请求的所有数据置于一种状态。

这是我目前收到的错误:
TypeError: Cannot read property 'setState' of null(…)

谢谢

最佳答案

您不能将数组“添加”在一起。使用array.concat函数(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)将两个数组合并为一个,然后将其设置为状态。

componentWillMount() {

   // Make a request for vehicle data

   axios.all([
     axios.get('/api/seat/models'),
     axios.get('/api/volkswagen/models')
   ])
   .then(axios.spread(function (seat, volkswagen) {
     let vehicles = seat.data.concat(volkswagen.data);
     this.setState({ vehicles: vehicles })
   }))
   //.then(response => this.setState({ vehicles: response.data }))
   .catch(error => console.log(error));

}

关于javascript - 多个Axios请求进入ReactJS状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38529553/

10-11 12:39
查看更多