如何将其他参数传递给useSelector

时间:2020-06-24 00:10:36

标签: reactjs redux react-redux

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

const productId = 25; // whatever

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

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

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);

2 个答案:

答案 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