gpt4 book ai didi

reactjs - 如何将附加参数传递给 useSelector

转载 作者:行者123 更新时间:2023-12-03 15:18:26 24 4
gpt4 key购买 nike

我调用 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);

最佳答案

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

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

关于reactjs - 如何将附加参数传递给 useSelector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62545632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com