useState的setter保证是一样的吗?
is the useState's setter guaranteed to be the same?
假设我想创建经常需要的 useInputState
挂钩:
function useInputState(initialValue) {
const [value, setValue] = useState(initialValue);
const onChange = useCallback(
e => setValue(e.target.value),
[ /* ??? */ ]
);
return { value, onChange };
}
我是否需要将 setValue
setter 函数添加到回调的依赖项中?
我们可以指望 setter 始终保持不变吗?
当我尝试时,这似乎有效,但这是好的做法吗?或者我们是否应该假设回调闭包中的任何内容都可以更改并影响其实现?
(我能想到更多最终提出相同问题的例子)
是的,useState
状态setter是同一个功能;即使它不会,也应该更新状态。它应该像问题显示的那样使用。
常用用法在 useReducer
documentation 中有更好的解释:
useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.
和useState
uses useReducer
internally.
对调用 useState
的范围的关注仅适用于 useState
状态值,该值在使用它的回调范围内保持不变,例如。如果要使用当前状态,则应使用状态更新程序函数检索它,例如 setValue(currentState => currentState + 1)
.
是的,来自 useState
的 setter 和来自 useReducer
的调度同样没有改变。
This portion of the docs 涵盖了通过上下文将 dispatch
方法传递给后代组件的模式,并包含以下内容:
If you use context to pass down the state too, use two different
context types — the dispatch context never changes, so components that
read it don’t need to rerender unless they also need the application
state.
假设我想创建经常需要的 useInputState
挂钩:
function useInputState(initialValue) {
const [value, setValue] = useState(initialValue);
const onChange = useCallback(
e => setValue(e.target.value),
[ /* ??? */ ]
);
return { value, onChange };
}
我是否需要将 setValue
setter 函数添加到回调的依赖项中?
我们可以指望 setter 始终保持不变吗?
当我尝试时,这似乎有效,但这是好的做法吗?或者我们是否应该假设回调闭包中的任何内容都可以更改并影响其实现?
(我能想到更多最终提出相同问题的例子)
是的,useState
状态setter是同一个功能;即使它不会,也应该更新状态。它应该像问题显示的那样使用。
常用用法在 useReducer
documentation 中有更好的解释:
useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.
和useState
uses useReducer
internally.
对调用 useState
的范围的关注仅适用于 useState
状态值,该值在使用它的回调范围内保持不变,例如setValue(currentState => currentState + 1)
.
是的,来自 useState
的 setter 和来自 useReducer
的调度同样没有改变。
This portion of the docs 涵盖了通过上下文将 dispatch
方法传递给后代组件的模式,并包含以下内容:
If you use context to pass down the state too, use two different context types — the dispatch context never changes, so components that read it don’t need to rerender unless they also need the application state.