【问题标题】:How to Normalize state in redux using Normalizr如何使用 Normalizr 规范化 redux 中的状态
【发布时间】:2021-08-13 09:31:51
【问题描述】:

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

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"
            }
          }
        }
      }
    }
  }
}

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案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);
    

    我得到下一个console output

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 2019-03-24
      • 2016-10-28
      • 1970-01-01
      • 2017-06-23
      • 2018-10-19
      • 2016-11-24
      • 2016-06-10
      • 2021-04-14
      相关资源
      最近更新 更多