多个 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({车辆: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屋!