14

因此,我一直在我的 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(…)

谢谢

4

4 回答 4

18

您不能将数组“添加”在一起。使用 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));

}
于 2016-07-22T15:05:57.953 回答
2

这有两个问题:

1)在您的 .then 中,“this”未定义,因此您需要在顶层存储对此的引用。

2)正如另一个答案所述,您不能像这样在JS中将数组添加在一起并且需要使用concat,尽管由于它们是服务器响应,我也会添加一个默认值以阻止它出错,如果其中任何一个不' t 实际上还给你一些东西。

总之,我认为它应该看起来像:

componentWillMount() {

  // Make a request for vehicle data
  var that = this;
  axios.all([
    axios.get('/api/seat/models'),
    axios.get('/api/volkswagen/models')
  ])
  .then(axios.spread(function (seat, volkswagen) {
    var seatData = seat.data || [];
    var volkswagenData = volkswagen.data || [];
    var vehicles = seatData.concat(volkswagenData);
    that.setState({ vehicles: vehicles })
  }))
  .catch(error => console.log(error));
}
于 2016-07-25T01:22:04.417 回答
2

我想提一些不同的东西。根据反应生命周期,您应该更喜欢在componentDidMount()方法中调用api。

“componentDidMount() 在组件安装后立即调用。需要 DOM 节点的初始化应该在这里。如果您需要从远程端点加载数据,这是实例化网络请求的好地方。”

https://reactjs.org/docs/react-component.html#componentdidmount

于 2017-11-28T18:29:10.090 回答
1
constructor(){
        super();
        this.state = {};
    }

    componentDidMount(){
        axios.all([
            axios.post('http://localhost:1234/api/widget/getfuel'),
            axios.post('http://localhost:1234/api/widget/getdatarate')
        ])
            .then(axios.spread((fuel,datarate) => {
                this.setState({
                    fuel:fuel.data.data[0].fuel,
                    datarate:datarate.data.data[0].data
                })
            console.log(this.state.fuel)
            console.log(this.state.datarate)

            }))
    }
于 2017-04-27T11:32:18.737 回答