简体   繁体   English

多个Axios请求进入ReactJS状态

[英]Multiple Axios Requests Into ReactJS State

So I have been placing the following code within my React JS component and I am basically trying to put both API calls into one state called vehicles however I am getting an error with the following code: 所以我一直在我的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));
  }

Now I am guessing I can't add two sources of data like I have this.setState({ vehicles: seat.data + volkswagen.data }) however how else can this be done? 现在我猜我不能添加两个数据源,比如我有this.setState({ vehicles: seat.data + volkswagen.data })但是怎么办呢? I just want all of the data from that API request to be put into the one state. 我只是希望将来自该API请求的所有数据放入一个状态。

This is the current error I am receiving: 这是我收到的当前错误:

TypeError: Cannot read property 'setState' of null(…)

Thanks 谢谢

You cannot "add" arrays together. 您不能将数组“添加”在一起。 Use the array.concat function ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat ) to concatenate both arrays into one and then set that as the state. 使用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));

}

There are two issues with this: 这有两个问题:

1) In your .then "this" is undefined, so you'll need to store a reference to this at the top layer. 1)在你的.then中,“this”是未定义的,所以你需要在顶层存储对它的引用。

2) As the other answer stated, you can't add arrays together in JS like that and need to use concat, although since they're server responses I'd add a default as well to stop it erroring if either of those don't actually return you something. 2)正如另一个答案所述,你不能像JS一样在JS中添加数组,并且需要使用concat,虽然因为它们是服务器响应我也会添加一个默认值来阻止它出错,如果其中任何一个不在实际上回报你的东西。

All together I think it should look like: 总之,我认为它应该是这样的:

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));
}

I want to mention something different. 我想提一些不同的东西。 According to the react life cycle, you should prefer call api in componentDidMount() method. 根据反应生命周期,您应该更喜欢在componentDidMount()方法中调用api。

"componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request." “componentDidMount()在安装组件后立即被调用。需要DOM节点的初始化应该在这里。如果你需要从远程端点加载数据,这是一个实例化网络请求的好地方。”

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

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)

            }))
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM