如何使用 Normalizr 在 redux 中标准化状态

IT技术 javascript reactjs redux react-redux
2021-05-16 08:09:36

我有一个嵌套的对象数组,如下所示:

var posts = [
   {
     _id:1234,
     body:"text",
     comments:[
        {
         _id:234,
         body:"hello world",  {
         ]
       },
       {
         _id:434,
         body:"hello world",
         replies:[
            {
              _id:0e2345,
              body:"hello",
            {
         ]
       }
     ]
   }
]

我想使用 normalizr 来简化数组并与 redux 一起使用。我已经阅读了 Normalizr 文档,但它的例子很少,我不知道我做错了什么。

我尝试了以下代码但没有成功。我得到的结果是一个未定义的数组。

export function getPosts(state, action) {
  const { payload } = action;
  const { data} = payload;
  const normalized = new schema.Entity("posts", {}, { idAttribute: "_id",});
  const normalizedData = normalize(data, [normalized]);

  return {
    ...state,
    normalizedData,
  };
}

我需要这样的东西:

entities:{
    posts:{
       123:{
        _id:123,
        body:"hello world",
        comments:{
          234:{
            _id:234,
            body:"hello world",
            replies:{
              0e2345:{
              _id:0e2345,
              body:"oh no"
            }
          }
        }
      }
    }
  }
}
1个回答

我尝试使用 JSON 对象重现此内容:

[{
    "_id":1234,
    "body":"text",
    "comments":[
       {
        "_id":234,
        "body":"hello world"  }
        ]
},
      {
        "_id":434,
        "body":"hello world",
        "replies":[
           {
             "_id":0e2345,
             "body":"hello"
           }
        ]
      }
    ]

并在代码中制作结构:

import data from "./data.json";
import { normalize, schema } from "normalizr";

const _id = new schema.Entity('_id');
const body = new schema.Entity('body');

  const normalized = new schema.Entity("posts", {
    posts:{
      _id:{
        _id:_id,
        body:body,
        comments:{
          _id:{
            _id:_id,
            body:body,
            replies:{
              _id:{
              _id:_id,
              body:body
            }
          }
        }
      }
    }
    }
  });
  
const normalizedData = normalize(data, [normalized]);

console.log(normalizedData);

我得到下一个控制台输出