如何编写既可重用又可模块化的 Redux 选择器? [英] How to write Redux selectors that are both reusable and modular?

查看:43
本文介绍了如何编写既可重用又可模块化的 Redux 选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Redux 的新手,并试图弄清楚如何充分利用它.

I am new to Redux and trying to figure out how to take full advantage of it.

在为应用程序的模块编写选择器时,应该将状态树的哪一部分传递给选择器,以便选择器既可重用又可模块化?

When writing a selector for a module of the application, what part of the state tree should be passed to the selector so that the selector is both reusable and modular?

例如,给定下面的代码,使用类似于 stateShapeExample 的状态形状编写 selectModuleItemsById 的好方法是什么?

For example, given the code below, what is a good way to write selectModuleItemsById with a state shape similar to stateShapeExample?

let stateShapeExample = {
    module: {
        items: {
            firstItemId: {...},
            secondItemId: {...},
            ...
        }
    }
}

const selectModuleRoot = (state) => state.module;

// First Option: starts from the module root
const selectModuleItemById = (state, id) => state.items[id];

// Second Option: starts from the global root
const selectModuleItemById = (state, id) => state.module.items[id];

// Something Else: ???
const selectItemById = (state, id) => state[id];

推荐答案

简而言之,它非常棘手.

The short answer is that it's pretty tricky.

我见过的最好的文章是 Randy Coulman 关于模块化选择器的系列文章:

The best writeup on this that I've seen is Randy Coulman's series of posts on modularizing selectors:

总体总结似乎是让模块缩减器"编写知道如何从自己的状态中挑选数据片段的选择器,然后根据模块/切片的安装位置在应用程序级别全球化"它们在状态树中.但是,由于模块可能需要使用选择器本身,您可能需要将注册/设置过程移到一个单独的文件中,以避免循环依赖问题.

The general summary of that seems to be letting "module reducers" write selectors that know how to pick pieces of data out of their own state, then "globalizing" them at the app level based on where that module/slice is mounted in the state tree. However, since the module probably needs to use the selectors itself, you may have to move the registration / setup process into a separate file to avoid a circular dependency issue.

这篇关于如何编写既可重用又可模块化的 Redux 选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆