[英]Spread operator on array of objects returns empty array
TL;DR: If value is unexpectedly gone or undefined or null etc. go and see the async functions. TL;DR:如果值意外消失或未定义或为空等,请查看异步函数。
There are some questions about spread operator returning "undefined" but in my case I got absolutely nothing.有一些关于传播运算符返回“未定义”的问题,但在我的情况下,我完全没有得到任何信息。
This is the process这是过程
[listof_objA, listof_objB]
函数 A 是一个异步函数并返回一个[listof_objA, listof_objB]
.then(([listof_objA, listof_objB])=> { ...so on
函数被评估后,结果像这样使用.then(([listof_objA, listof_objB])=> { ...so on
dispatch(setListA(listof_objA))
like然后分派dispatch(setListA(listof_objA))
像someAsyncFunc().then(([listof_objA, listof_objB])=> {
dispatch(setListA(listof_objA))
dispatch(setListB(listof_objB))
})
console.log(action.payload)
, it correctly displays the obtained listof_objA
在reducer中console.log(action.payload)
,正确显示获取到的listof_objA
case Types.SET_LISTA: {
console.log(action.payload)
return {
...state,
listof_objA: action.payload
}
}
case Types.SET_LISTA: {
console.log(action.payload)
return {
...state,
listof_objA: [...action.payload]
}
}
[]
.例如) []
。 The action.payload
still correctly displays the obtained listof_objA
. action.payload
仍然正确显示获得的listof_objA
。JSON.parse(JSON.stringify(action.payload))
, const newList = [...action.payload]
我试过JSON.parse(JSON.stringify(action.payload))
, const newList = [...action.payload]
Array(0)
but when dropped down it shows Array(13) [{...},{...}, ... , {...}]
.折叠的动作显示有效载荷是Array(0)
但当下拉时它显示Array(13) [{...},{...}, ... , {...}]
。This is it.就是这个。 I couldn't find any solution.我找不到任何解决方案。 I don't know why this is happening.我不知道为什么会这样。 And it seems it happened only to me.而且似乎只发生在我身上。 Please help.请帮忙。 If you need anymore information please comment.如果您需要更多信息,请发表评论。 I am working with a company so I can't provide all information.我在一家公司工作,所以我不能提供所有信息。 But I'll try my best.但我会尽力的。 Thank you.谢谢你。
I guess you are using a Promise in someAsyncFunc
, If so, the reason you get an empty array is because you probably didn't resolved your Promise chain correctly.我猜你在someAsyncFunc
中使用了一个 Promise ,如果是这样,你得到一个空数组的原因是因为你可能没有正确解析你的 Promise 链。
The correct Promise chain should look like this:正确的 Promise 链应如下所示:
async function someAsyncFunc() {
return await fetch('ENDPOINT')
.then(response => {
return response.ok
? response.json()
: Promise.reject(Error('Unsuccessful response'));
})
.then(([listof_objA, listof_objB]) => {
dispatch(setListA(listof_objA));
dispatch(setListB(listof_objB));
});
}
In order to read the body of the responses JSON.为了读取响应 JSON 的正文。 You need to call the response.json() method.您需要调用 response.json() 方法。 The json() method reads the full body of the response and parses the text as a JSON. json() 方法读取响应的完整正文并将文本解析为 JSON。 Since this is another asynchronous operation it returns a promise itself.由于这是另一个异步操作,它本身返回一个承诺。
Hope that it helps希望它有帮助
@jank 回答我希望能解决你的问题,但你可能想看看redux-api-middleware作为一种更简单的 RPC 调用方式,没有所有的承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.