我应该将 useSelector 传递给 useState [英] Should I pass useSelector to useState

查看:26
本文介绍了我应该将 useSelector 传递给 useState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我对您更喜欢哪种方法有疑问:

Hello guys I have question regarding which method you prefer:

在带有 TypeScript 的 React 功能组件中,使用 useSelector 从 Redux State 获取值是:1)

In a React functional component with TypeScript, that gets values from Redux State using useSelector is: 1)

 const campaign = useSelector(campaignSelector);
 const [audienceSample, setAudienceSample] = useState<number | null>((campaign || 
  {max_completes_total: null})['max_completes_total']);

来自2)

 const campaign = useSelector(campaignSelector);
  const [audienceSample, setAudienceSample] = useState<number | null>(null);
  useEffect(() => {
    setAudienceSample(campaign.max_completes_total)
     },[campaign])

我知道 1 代码更少,但你认为它更快吗?你更喜欢哪一个谢谢各位

I know 1 is less code but do you think it is faster and which one would you prefer thank you guys

推荐答案

第一个无效.它是无效的,因为来自 useState 的状态是持久的,并且在 useState 中设置的参数是 default 值,它的意思是 - 它只有在第一次安装组件时才会设置.因此,更改 redux 状态和 useSelector 给出的新值不会影响本地状态,它将始终指示原始默认值.

The first is invalid. And it is invalid because state from useState is persistent, and the argument which is set in useState is default value, what it means is - it will be set only when component mounts for the first time. So changing of the redux state and new value given from useSelector will not effect the local state, it will indicate all the time the original default value.

回答你的问题——答案不是我喜欢什么,而是什么有效,第二个才是正确的.然而,我在这里提出的从代码角度来看的最佳解决方案是将两者合并,以避免将 null 设置为默认值并在 useState 中设置泛型类型.考虑以下代码:

Answering your question - the answer is not about what I prefer, but what works, the second is just the proper one. However what I would propose here as the best solution from the code perspective is to merge little bit both, in order to avoid setting null as default and setting generic types in useState. Consider following code:

const campaign = useSelector(campaignSelector);
const [audienceSample, setAudienceSample] = useState(campaign?.max_completes_total); // set campaign as default

useEffect(() => {
   setAudienceSample(campaign?.max_completes_total)
},[campaign]) // set the relation between redux campaign and local state

此外,如您所见,我使用了 可选链以简化代码.本地状态的类型将自动推断为 number |未定义.

Additionally as you see I have used optional chaining in order to simplify the code. The type of the local state will automatically be inferred as number | undefined.

最重要的是,我理解你的情况是在 redux 和本地状态之间建立关系,然后第二个是唯一的选择.如果您只想设置默认值,则根本不需要使用 useEffect.

Above all as I understood your case is to have a relation between redux and local state, then the second is the only option. If your intention was to set only the default value, then using useEffect is not needed at all.

这篇关于我应该将 useSelector 传递给 useState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆