多个Axios请求进入ReactJS状态 [英] Multiple Axios Requests Into ReactJS State
问题描述
所以我一直在我的React JS组件中放置以下代码,我基本上试图将两个API调用放入一个名为 vehicles
的状态但是我收到错误使用以下代码:
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:
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请求的所有数据放入一个状态。
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? I just want all of the data from that API request to be put into the one state.
这是我收到的当前错误:
This is the current error I am receiving:
TypeError: Cannot read property 'setState' of null(…)
谢谢
推荐答案
您无法将数组添加在一起。使用array.concat函数( https:// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat )将两个数组连接成一个,然后将其设置为状态。
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.
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));
}
这篇关于多个Axios请求进入ReactJS状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!