本文介绍了如何将附加参数传递给 useSelector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am calling useSelector successfully from a component, which derives a product name from an id.

const productId = 25; // whatever

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

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

However, my selector is dependent on productId, which I'm storing in a variable in the same file. I'd like to store this useSelector call in an external file so it can be shared. I tried the following, but id is 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);

推荐答案

不幸的是,selector 函数只接受商店的状态作为参数.我会考虑使用柯里化方法来解决这个问题:

unfortunately, selector function accepts only store's state as argument. I would consider to use a currying approach to tackle the issue:

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

这篇关于如何将附加参数传递给 useSelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 21:30