gpt4 book ai didi

reactjs - 在应用程序中多次使用 useSelector react redux

转载 作者:行者123 更新时间:2023-12-02 16:37:10 27 4
gpt4 key购买 nike

您好,我在我的应用程序中多次使用选择器。我可以编写一次代码然后导入选择器吗?我想写一个自定义钩子(Hook),但我认为这是没有必要的。这是我的选择器:

const county = useSelector((state)=>{
const id = state.user.id
const name = state.user.name
return state.users.filter((user) => user.name === name)[0].county
})

如果我有这样的东西就好了:

import {countySelector} from 'selectors'
const county = useSelector(countySelector)

最佳答案

可以在useSelector中传递箭头函数

export const countySelector = state => {
const id = state.user.id;
const name = state.user.name;
return state.users.find(user => user.name === name).county;
};

// Usage
import { countySelector } from 'selectors';
const county = useSelector(countySelector);

或者创建自定义钩子(Hook)

const useCounty = () => {
return useSelector(state => {
const id = state.user.id;
const name = state.user.name;
return state.users.find(user => user.name === name).county;
});
};

export default useCounty;

// Usage
import useCounty from 'useCounty';
const county = useCounty();

关于reactjs - 在应用程序中多次使用 useSelector react redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62449761/

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