【发布时间】:2023-10-31 13:50:01
【问题描述】:
我有一个 React 应用程序,我在其中使用 Redux 和 Redux-Saga 并 Reselect 作为选择器库(使用 Immer 来处理 Redux 状态的不变性)。我写这个问题是因为我想了解我处理带参数的选择器的方法是否完全正确。
我个人更喜欢避免在 sagas 中使用 yield select,因为我想保留中间件 not depend on the Store's state,但我的旧代码中包含带有 yield select 的 sagas。
下面是我必须编写的代码来实现我的选择器并将他调用到组件和传奇中。我从Reselec doc 获得了选择器实现。
// selectors.js: Selector implementation
const makeGetPerson = createSelector(
getPersonsList,
(state, id) => id,
(persons, id) => persons.find((person) => person.id === id)
);
// components.js: if I have to use the selector into a component
const person = useSelector((state) => makeGetPerson(state, id))
// saga.js: if I have to use the selector into a saga
const persons = yield select(getPersonsList)
const person = persons.find((person) => person.id === id)
目前,我必须使用返回元素列表的选择器并手动过滤它们。有没有办法在 a saga 中做类似yield select((state) => getPersonsList(state, id)) 的事情?我还缺少其他方法吗?
【问题讨论】:
-
吹毛求疵:不要调用选择器
makeGetPerson。 “make”前缀通常用于“选择器工厂”,每次调用时都会返回一个新的选择器实例。这不是“工厂”——它是选择器函数本身。就叫它getPerson或selectPerson。有关详细信息,请参阅 Redux 文档 Deriving Data with Selectors 页面。
标签: reactjs redux redux-saga reselect immer.js