使用useState挂钩时,仅更新部分状态并保持其他状态不变

时间:2019-12-12 01:06:54

标签: javascript reactjs react-hooks

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

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'}

1 个答案:

答案 0 :(得分:2)

这是我想用于这种情况的自定义钩子。我称其为useLegacyState(),因为这模仿了较早的类组件状态所具有的行为:

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' }
相关问题