Javascript 多个 Axios 请求进入 ReactJS 状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38529553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple Axios Requests Into ReactJS State
提问by Nick Maddren
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? I just want all of the data from that API request to be put into the one state.
现在我猜我不能像我一样添加两个数据源,this.setState({ vehicles: seat.data + volkswagen.data })
但是还能怎么做?我只想将来自该 API 请求的所有数据都放入一个状态。
This is the current error I am receiving:
这是我收到的当前错误:
TypeError: Cannot read property 'setState' of null(…)
Thanks
谢谢
回答by erichardson30
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));
}
回答by yasinv
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
回答by Ben Hare
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 中将数组添加在一起,并且需要使用 concat,尽管因为它们是服务器响应,我也会添加一个默认值以阻止它在其中任何一个不出错的情况下出错t 实际上还给你一些东西。
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));
}
回答by Rinoyrix
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)
}))
}