GET 和 setState 之后无法读取数组,即使它在那里
GET 请求提取特定用户下达的所有订单。设置很奇怪,但确实能正确提取数据。
var all = [];
axios.get('/api/orders/' + this.props.user.name)
.then(function (res) {
res.data.forEach(e => {
e.orders.forEach(eachOrder => {
all.push (
eachOrder
)
})
})
console.log('this be all: ', all);
})
this.setState({
orders : all
});
eachOrder 会打印订单(针对每个订单):
{type: "Pizza", extraType: "na", extraInfo: "na", date: "", quantify: "1", …
这都是 console.log :
(5) [{…}, {…}, {…}, {…}, {…}]
0: {type: "Pizza", extraType: "na", extraInfo: "na", date: "", quantity: "1", …}
1: {type: "na", extraType: "Can", extraInfo: "Diet Coke", date: "", quantity: "1", …}
2: {type: "na", extraType: "Can", extraInfo: "Diet Coke", date: "", quantity: "1", …}
3: {type: "na", extraType: "1 Pound", extraInfo: "Honey Garlic", date: "", quantity: "1", …}
4: {type: "na", extraType: "1 Pound", extraInfo: "Honey Garlic", date: "", quantity: "1", …}
length: 5
__proto__: Array(0)
完美,正如我所期望的那样。我将州的订单设置为全部..但订单似乎很奇怪?
if (this.state.orders !== null) {
console.log('lets see the order: ', this.state.orders)
}
让我们看看订单..:
[]
0: {type: "Pizza", extraType: "na", extraInfo: "na", date: "", quantity: "1", …}
1: {type: "na", extraType: "Can", extraInfo: "Diet Coke", date: "", quantity: "1", …}
2: {type: "na", extraType: "Can", extraInfo: "Diet Coke", date: "", quantity: "1", …}
3: {type: "na", extraType: "1 Pound", extraInfo: "Honey Garlic", date: "", quantity: "1", …}
4: {type: "na", extraType: "1 Pound", extraInfo: "Honey Garlic", date: "", quantity: "1", …}
length: 5
__proto__: Array(0)
我无法检查订单的
.length
,无法
map
或
forEach
,什么都做不了。我无法检查数组中的元素。
知道发生了什么吗?
您需要在 http 异步请求的回调中
setState
。您收到承诺拒绝错误是因为您的
this
引用被重定向到
function(res) {
。
当您使用
function
关键字进行回调而不是 ES6 箭头函数(也是编写 React 组件方法的最佳实践)时,这种情况经常发生
您可以这样做,将
function() {
替换为
() => {
:
var all = [];
axios.get('/api/orders/' + this.props.user.name)
.then((res) => { //change function to arrow function
res.data.forEach(e => {
e.orders.forEach(eachOrder => {
all.push (
eachOrder
)
})
})
this.setState({
orders : all
});
console.log('this be all: ', all);
})
或者,如果您需要或想要继续使用
function
关键字作为回调,您可以将组件方法变成箭头函数以将
this
的引用绑定到组件
mySexyMethod = () => {
var all = [];
axios.get('/api/orders/' + this.props.user.name)
.then(function (res) {
res.data.forEach(e => {
e.orders.forEach(eachOrder => {
all.push (
eachOrder
)
})
})
this.setState({
orders : all
});
console.log('this be all: ', all);
})
}
但无论您决定采用哪种解决方案,问题的第一个也是最重要的部分是您的
setState
不在您的异步请求的回调中,只需将其移到块中即可使其工作。
对
then
块使用箭头函数,并将
setState
移到内部。这样就可以了。
查看此文档,它可能会有所帮助 https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html
这应该可行。至少这对这里的男性有效 https://github.com/mustafamamun/Test/blob/master/UI/src/App.js
axios.get('/api/orders/' + this.props.user.name)
.then(res=> {
res.data.forEach(e => {
e.orders.forEach(eachOrder => {
all.push (
eachOrder
)
})
})
console.log('this be all: ', all);
this.setState({
orders : all
});
})