且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

React Hooks useReduce 或 useState

更新时间:2022-12-13 08:14:59

来自 useReducer文档:

useReducer 通常比 useState 更可取,当您有涉及多个子值的复杂状态逻辑或下一个状态依赖于前一个时.

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

您应该使用 useReducer 来管理您的复杂表单,否则您最终将拥有许多 useState 和许多 useEffects 来更新所有其他状态useState 变化.在这种情况下,useReducer 无疑是***的选择.

You should use the useReducer to manage you complex form, otherwise you'll end up having many useState and a many useEffects to update every other state when one of those useState changes. In this case useReducer is definetevely the best option.

通过这种方式,您的所有 UI 元素都将是 useReducer 状态的可视化表示,因此字段中的任何值更改都必须触发更新状态和 UI 的操作.

In this way all your UI elements will be a visual representation of the useReducer state, so any value change in a field must trigger an action to update the state and then the UI.

您也可以尝试使用现有的库,例如 react-hook-form,但此选择取决于您并取决于您的要求.

You can also try using an existing library like react-hook-form, but this choise is up to you and depends on your requirements.