客户挂钩中的 useReducer 不更新 UI
useReducer in customer hooks does not update the UI
我想用一个useReducer实现一个像官方文档中提到的useLegacyState这样的自定义hooks来灵活的更新组件中的state
https://reactjs.org/docs/hooks-faq.html#should-i-use-one-or-many-state-variables
只能使用useState或useReducer实现:
https://codesandbox.io/embed/usereducer-update-any-05v82
但是,我无法使用自定义挂钩更新 UI:
https://codesandbox.io/embed/customer-usestates-xxn01
为什么?
您需要更新您的 reducer 函数:
function reducer(state, action) {
return Object.assign({}, state, action);
}
原因是
当您执行 Object.assign(state, action)
时,state
也会使用 action
中的属性进行更新,这会导致 React 无法从更新的 state
中伪装原始的 state
,因此 shouldComponentUpdate returns false 因为状态和更新后的状态相同。
我想用一个useReducer实现一个像官方文档中提到的useLegacyState这样的自定义hooks来灵活的更新组件中的state
https://reactjs.org/docs/hooks-faq.html#should-i-use-one-or-many-state-variables
只能使用useState或useReducer实现:
https://codesandbox.io/embed/usereducer-update-any-05v82
但是,我无法使用自定义挂钩更新 UI:
https://codesandbox.io/embed/customer-usestates-xxn01
为什么?
您需要更新您的 reducer 函数:
function reducer(state, action) {
return Object.assign({}, state, action);
}
原因是
当您执行 Object.assign(state, action)
时,state
也会使用 action
中的属性进行更新,这会导致 React 无法从更新的 state
中伪装原始的 state
,因此 shouldComponentUpdate returns false 因为状态和更新后的状态相同。