【问题标题】:Structuring Redux state by domain?按域构建 Redux 状态?
【发布时间】:2016-04-29 02:13:42
【问题描述】:

在检索具有不同搜索参数的域对象时,应如何构造 Redux 状态。

在我的应用程序中,我在表格中显示用户过滤的organisations 列表。在同一页面上,我还将显示一个用户所属的组织的较小列表,并且将来可能会在同一页面上显示另一个仅显示来自另一个用户的组织的小列表。

我会这样做吗:

{
    list_organisations: [
        { id: 1, name: 'foo1' //... },
        { id: 2, name: 'foo2' //... },
        { id: 3, name: 'foo3' //... },
        { id: 4, name: 'foo4' //... },
        { id: 5, name: 'foo5' //... },
    ],
    user_one_organisations: [
        { id: 6, name: 'foo' //... },
        { id: 2, name: 'foo' //... },
    ],
    user_two_organisations: [
        { id: 4, name: 'foo' //... },
        { id: 6, name: 'foo' //... },
    ],  
}

或者这个:

{
    users: [
        { id: 1, organisations: [7,3,8], name: 'billy' },
        { id: 2, organisations: [3,6,1], name: 'sam' },
    ]
    organisations: [
        { id: 1, name: 'foo', //... },
        { id: 2, name: 'foo1', //... },
        { id: 3, name: 'foo2', //... },
        { id: 4, name: 'foo3', //... },
        { id: 5, name: 'foo4', //... },
        { id: 6, name: 'foo5', //... },
        { id: 7, name: 'foo6', //... },
        { id: 8, name: 'foo7', //... },
        { id: 9, name: 'foo8', //... },
    ],  
}   

如果我们选择选项二,如果出于某种目的需要查找单个组织,我们该怎么办,例如。 “检查一个用户的电子邮件是否存在于一个组织中”——这一切看起来都很复杂......尤其是在做一次性请求时?它甚至应该处于 redux 状态吗?

那就是这样:

{
    users: [
        { id: 1, organisations: [7,3,8], name: 'billy' },
        { id: 2, organisations: [3,6,1], name: 'sam' },
    ]
    organisation_signup_form: {
        doesUsersEmailExist: true / false / null,
    }
    organisations: [
        { id: 1, name: 'foo', //... },
        { id: 2, name: 'foo1', //... },
        { id: 3, name: 'foo2', //... },
        { id: 4, name: 'foo3', //... },
        // ...
    ],  
}   

【问题讨论】:

    标签: javascript reactjs state redux react-redux


    【解决方案1】:

    我实际上建议以完全不同的方式构建您的数据。您要确保所有模型都很容易上手,因此将它们放在一个数组中可能会很棘手。

    我建议一个类似这样的状态结构:

    users: {
        1: { id: 1, organisations: [7,3,8], name: 'billy' },
        2: { id: 2, organisations: [3,6,1], name: 'sam' },
    },
    userList: [1,2],
    organisation_signup_form: {
        doesUsersEmailExist: true / false / null,
    },
    organisations: {
        1: { id: 1, name: 'foo', //... },
        2: { id: 2, name: 'foo1', //... },
        3: { id: 3, name: 'foo2', //... }
    }
    

    我从 Dan 那里得到了这个 question 的建议

    检查组织内是否存在用户电子邮件

    您没有关于用户模型的电子邮件,并且不清楚,因此很难回答这个具体问题。

    我要给出的一点建议是,您需要以一种数据库的方式来构建您的状态,但它不必与您的实际数据库或 api 端点具有相同的结构。

    【讨论】:

    • 嗯,我喜欢。虽然我是否使用这种结构从我的 API 服务器响应?或者在减速器中构建它?我希望我的 API 不是 redux 特定的 :)
    • 没错,让你的 api 保持真实。客户端实现应该定义如何返回数据。它可以影响它,但不能定义它。
    • 酷。最后一个问题!是否有一个巧妙的技巧来用他们的 ID 键入实体?我不想要重型减速机?
    • 我使用不变性助手并执行以下操作:{[action.user.id]: action.user}facebook.github.io/react/docs/update.html
    猜你喜欢
    • 2019-05-24
    • 2021-08-27
    • 2019-03-09
    • 2021-10-10
    • 2018-09-18
    • 2022-01-17
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多