React - useState 的 setter 函数可以改变吗? [英] React - Is useState 's setter function able to change?

查看:37
本文介绍了React - useState 的 setter 函数可以改变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

useState 的 setter 是否可以在组件生命周期内改变?

例如,假设我们有一个 useCallback 将更新状态.如果 setter 能够更改,则必须将其设置为回调的依赖项,因为回调使用它.

const [state, setState] = useState(false);const 回调 = useCallback(() =>设置状态(真),[setState]//<--);

解决方案

setter 函数在组件生命周期内不会改变.

来自 Hooks 常见问题解答:

<块引用>

(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.

From Hooks FAQ:

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆