我正在从一个组件成功调用useSelector
,该组件从id派生产品名称。
const productId = 25; // whatever
const productName = useSelector(
(state) =>
state.dashboard.dashboards.filter(
({ Id }) => Id === productId
)[0].Name
);
但是,我的选择器依赖于productId
,我将其存储在同一文件的变量中。我想将此useSelector
调用存储在一个外部文件中,以便可以共享。我尝试了以下操作,但是id
是undefined
:
selectors.js
export const getProductNameById = (store, id) => {
return store.dashboard.dashboards.filter(({ Id }) => Id === id)[0]
.Name;
}
some_file.js
import { useSelector } from "react-redux";
import { getProductNameById } from "./selectors";
const productId = 25;
const productName = useSelector(getProductNameById, productId);
答案 0 :(得分:11)
不幸的是,selector
函数仅接受商店的状态作为参数。我会考虑使用一种简单的方法来解决该问题:
export const getProductNameById = id => store => {
return store.dashboard.dashboards.filter(({ Id }) => Id === id)[0]
.Name;
}
某些文件
import { useSelector } from "react-redux";
import { getProductNameById } from "./selectors";
const productId = 25;
const productName = useSelector(getProductNameById(productId));
答案 1 :(得分:2)
似乎是这样的:
const productName = useSelector((state) => getProductNameById(state, productId));
这是redux docs教程似乎如何处理此问题的方式。 here