在React Redux中建模状态树

时间:2016-03-29 19:28:50

标签: reactjs redux

我试图学习redux,而我不清楚的一件事是如何在状态树中建模数据。采用简单的evernote类型应用程序,其中有许多笔记本,每个笔记本都有许多笔记。状态树的一种可能表示是这样的:

{
  notebooks:[
    {
      id: 0
      notes:[
        "hey",
        "ho",
        "let's go"
      ]
    },
    {
      id: 1
      notes:[
        "another",
        "notebook"
      ]
    }
  ]
}

但是之后我也读了it's not good to have a deeply nested state tree而应该以更规范的方式存储状态,就像它是一个结构化数据库一样。那么在这种情况下,像这样建模数据会更好吗?

{
  notebooks: [
    {
      id: 0
    },
    {
      id: 1
    }
  ]
  notes: [
    {
      notebook_id: 0,
      note: "hey"
    }
    {
      notebook_id: 0,
      note: "ho"
    },
    {
      notebook_id: 0,
      note: "let's go"
    },
    {
      notebook_id: 1,
      note: "another"
    },
    {
      notebook_id: 1,
      note: "notebook"
    }
  ]
}

或者有第三种甚至更好的方法吗?

2 个答案:

答案 0 :(得分:1)

你做对了。如果您选择规范化数据,请查看Normalizr library

答案 1 :(得分:0)

关闭。对于嵌套/关系数据,您希望将Redux状态视为具有" tables"的数据库。如果你保留所有真实的"它通常是最容易的。按ID键入的查找表中的对象,然后所有其他引用只使用适当的ID:

{
    notebooks : {
        byId : {
            0 : { notes : [0, 4]},
            1 : { notes : [1, 2, 3]}
        },
        ordered : [0, 1]
    },
    notes : {
        byId : {
            0 : {notebook : 0, note : "hey"},
            1 : {notebook : 1, note : "ho"},
            2 : {notebook : 1, note : "let's go"},
            3 : {notebook : 1, note : "another"},
            4 : {notebook : 0, note : "notebook"}
        }
    }
}

根据其他评论,Normalizr库可以帮助解决这个问题。我也非常喜欢名为redux-orm的库,它有助于维护关系。

最后,您可能需要参考organizing nested state上的Redux常见问题答案。

相关问题