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));
}
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(…)
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.
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));
}