如何将附加参数传递给 useSelector

IT技术 reactjs redux react-redux
2021-05-23 18:15:53

useSelector从一个组件成功调用,该组件从 id 派生产品名称。

const productId = 25; // whatever

const productName = useSelector(
  (state) =>
    state.dashboard.dashboards.filter(
      ({ Id }) => Id === productId
    )[0].Name
);

但是,我的选择器依赖于productId,我将其存储在同一文件的变量中。我想将此useSelector调用存储在外部文件中,以便可以共享。我尝试以下,但idundefined

选择器.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);
3个回答

不幸的是,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));

似乎这样做的方法是这样的:

const productName = useSelector((state) => getProductNameById(state, productId));

这就是 redux docs 教程似乎如何处理这个问题。 这里

这也应该有效:

const productName = useSelector(getProductNameById(productId));