React Hooks useReduce 或 useState [英] React Hooks useReduce or useState
问题描述
我有一个包含 30 个字段的表单,所有这些字段都是来自下拉列表中的值的模板,如果我更改模板的值,我最终会创建一个自定义模板.
I have a form with 30 fields and all those fields are a template from a value in a dropdown, if I change the value of the template I will end up creating a custom template.
所以动作是:
- 当我们更改表单中的值时,模板将在自定义模板中更改
如您所见,有一些逻辑上下波动,我担心多个 setState 声明和调用.我应该使用 useReducer
还是 useState
?
As you can see there are some logic that come up and down and I'm worried about the multiple setState declaration and call. Should I use useReducer
or useState
?
推荐答案
来自 useReducer文档:
useReducer
通常比 useState
更可取,当您有涉及多个子值的复杂状态逻辑或下一个状态依赖于前一个时.
useReducer
is usually preferable touseState
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.
这篇关于React Hooks useReduce 或 useState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!