使用 useState 钩子时只更新状态的一部分并保持其他状态相同 [英] Updating just part of state and keeping others same when using useState hook

查看:56
本文介绍了使用 useState 钩子时只更新状态的一部分并保持其他状态相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我可以执行以下操作来仅更新状态的一部分并保持其他状态不变吗?

Hello can I do the following to update just a portion of state and keep others same?

const stuff ={ 'a':'alpha', 'b':'alpha' };

const [letter,setLetter]=useState(stuff);

// update
// can i do it this way?
setLetter(...letter,'a':'omega');

// will this result in:
// letter==={'a':'omega', 'b':'alpha'}

推荐答案

这是我喜欢用于这种情况的自定义钩子.我称之为 useLegacyState() 因为这模仿了旧类组件状态的行为:

Here's a custom hook I like to use for this situation. I call it useLegacyState() since this mimics the behavior that the older class component states have:

const useLegacyState = initialState => useReducer(
  (state, update) => ({ ...state, ...update }),
  initialState
);

// usage
const [letter, setLetter] = useLegacyState(stuff);

// update
setLetter({ a: 'omega' });

// will result in: { a: 'omega', b: 'alpha' }

这篇关于使用 useState 钩子时只更新状态的一部分并保持其他状态相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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