简体   繁体   English

如何将 map 对象数组转换为 Redux Slice 中的不同对象(具有不同属性)?

[英]How do I map an array of objects to different objects (with different properties) in a Redux Slice?

Trying to asynchronously filter and transform an array of objects that I receive from my backend.尝试异步过滤和转换我从后端收到的对象数组。 I'm using Redux with React to manage store.我正在使用 Redux 和 React 来管理商店。 Here's what I have now in my slice.js :这是我现在的slice.js中的内容:

...
export const getData = createAsyncThunk('foo/bar', async (address, thunkAPI) => {
    try {
        //returns an array of objects [{}, {}, ...]
        const allData = JSON.parse(await myService.getAllData(address));
        let newData = [];
        allData.forEach(async (data) => {
           if(*some filtering logic here*) {
               newData.push(await (fetch(data.uri).then(response => response.json())));
           }
        });
        return newData;
    } catch (error) {
        //handle error
    }
});

However, my newData array seems to be unpushable/marked as unextensible.但是,我的newData数组似乎无法推送/标记为不可扩展。 It gives the error它给出了错误

Uncaught (in promise) TypeError: Cannot add property 0, object is not extensible
    at Array.push (<anonymous>)

Some of the other solutions to this error ( React: cannot add property 'X', object is not extensible , https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible ) all mention React props/editing state variables, but I can't figure out why I cannot push to an empty array newData .此错误的其他一些解决方案( React: cannot add property 'X', object is not extensible , https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible )所有提到 React props/editing state 变量,但我不明白为什么我不能推送到一个空数组newData

You cannot do async in forEach , so you need a plain old for loop您不能在forEach中执行async操作,因此您需要一个普通的旧 for 循环

try {
        const allData = JSON.parse(await myService.getAllData(address));
        const newData = []; // not reassigning, use const
        for (let i = 0, n = allData.length; i < n; ++i) {
          if (*some filtering logic here*) {
            newData.push(await (fetch(data.uri).then(response => response.json())));
          }
        }
        return newData;
    }

This should work这应该工作

Hey There so with regards to your question here is another way you could achieve what you are looking to achieve let me know if this helps you out for future too maybe嘿,关于你的问题,这里有另一种方法可以实现你想要实现的目标让我知道这是否对你的未来也有帮助也许

try {
              //returns an array of objects [{}, {}, ...]
              const allData = JSON.parse(await myService.getAllData(address));
              let newData = [];
        // this will be an array of unresolved promises and then you can have them run in parallel with the promise all below
              const promises = allData.map((objectOfData) => fetch(objectOfData.uri))
                
    //this data will be the results
              const  data = Promise.all(promises)
    //do with the data what you want
              data.forEach((item) => {
                if(*some filtering logic here*) {
                   newData.push(item);
               }
    
              })
                return newData;
            } catch (error) {
                //handle error
            }

As for why this happens: it's a timing issue.至于为什么会这样:是时间问题。

Since you started the asynchronous side effect in sub-functions without ever awaiting them in the main thunk function, the thunk pretty much finished before anything of your fetch calls resolved.由于您在子函数中启动了异步副作用,而没有在主 thunk function 中等待它们,因此在您的任何fetch调用解决之前,thunk 几乎已经完成。 After that, you are copying that data into your store - and it gets frozen, so after that it cannot be modified any more.之后,您将该数据复制到您的商店中 - 它会被冻结,因此之后无法再对其进行修改。

=> wait in your thunk until actually all work is done. => 等待你的声音,直到所有的工作都完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问不同对象的属性? - How do I access properties from different objects? 如何根据不同的属性排序对象数组? - How to order an array of objects according to different properties? 我应该如何切片对象的对象数组 - How should I slice the array of objects of objects 如何通过比较两个不同的唯一属性来对不同大小的对象数组中的元素进行分组? 在 JavaScript 中 - How do group elements in an array of objects of different sizes by comparing two different unique properties? in javascript React map - 如何正确处理具有不同属性的对象 - React map - How to properly handle objects when they have different properties 在一个对象数组中结合两个不同对象数组的不同属性 - Combining different properties of two different arrays of objects in one array of objects 如何跨不同数组对象的属性传递数组的值 - How to pass values of an array across properties of different array objects 如何映射联系人数组以生成具有对象和属性的新数组? - How do I map over a contacts array to produce a new array with objects and properties? 如何通过反应 redux 中的对象数组 map - how to map through an array of objects in react redux 如何向对象数组添加新属性? 我正在尝试使用$ .map - How do I add new properties to an array of objects? I'm trying to use $.map
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM