React - useState 的 setter 函数可以改变吗? [英] React - Is useState 's setter function able to change?
问题描述
useState 的 setter 是否可以在组件生命周期内改变?
例如,假设我们有一个 useCallback
将更新状态.如果 setter 能够更改,则必须将其设置为回调的依赖项,因为回调使用它.
const [state, setState] = useState(false);const 回调 = useCallback(() =>设置状态(真),[setState]//<--);
setter 函数在组件生命周期内不会改变.
<块引用>(setCount 函数的身份保证是稳定的,所以省略是安全的.)
从 useState
返回的 setter 函数 (setState
) 在组件重新挂载时发生了变化,但无论哪种方式,callback
都会获得一个新的实例.
在使用自定义钩子时,在依赖数组([setState]
)中添加状态设置器是一个很好的做法.例如,react-redux 的
useDispatch
在每次渲染时获取新实例,如果没有:
//自定义钩子import { useDispatch } from react-redux";export const CounterComponent = ({ value }) =>{//总是新的实例const dispatch = useDispatch();//应该在回调中const incrementCounter = useCallback(() =>调度({ 类型:增量计数器"}),[派遣]);返回 (<div><span>{值}</span>//由于引用的改变,可能会不必要地渲染<MyIncrementButton onIncrement={dispatch}/>//在回调中,一切正常<MyIncrementButton onIncrement={incrementCounter}/>
);};
Is useState's setter able to change during a component life ?
For instance, let's say we've got a useCallback
which will update the state.
If the setter is able to change, it must be set as a dependency for the callback since the callback use it.
const [state, setState] = useState(false);
const callback = useCallback(
() => setState(true),
[setState] // <--
);
The setter function won't change during component life.
(The identity of the setCount function is guaranteed to be stable so it’s safe to omit.)
The setter function (setState
) returned from useState
changes on component re-mount, but either way, the callback
will get a new instance.
It's a good practice to add state setter in the dependency array ([setState]
) when using custom-hooks. For example, useDispatch
of react-redux
gets new instance on every render, you may get undesired behavior without:
// Custom hook
import { useDispatch } from "react-redux";
export const CounterComponent = ({ value }) => {
// Always new instance
const dispatch = useDispatch();
// Should be in a callback
const incrementCounter = useCallback(
() => dispatch({ type: "increment-counter" }),
[dispatch]
);
return (
<div>
<span>{value}</span>
// May render unnecessarily due to the changed reference
<MyIncrementButton onIncrement={dispatch} />
// In callback, all fine
<MyIncrementButton onIncrement={incrementCounter} />
</div>
);
};
这篇关于React - useState 的 setter 函数可以改变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!