首页 > 解决方案 > React useState 的 setter 是否会过时?

问题描述

我正在使用全局事件处理程序。为了避免在每次状态更改时分离/重新附加事件处理程序,我使用带有强制更新的 ref:

  const ref = useRef();
  const forceUpdate = useState()[1];

  const handlePopState = (event) => {
    ref.current = {
      ...ref.current,
      foo: event.foo,
    };
    forceUpdate();
  };

  useEffect(() => {
    window.addEventListener('popstate', handlePopState);

    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, []);

我很惊讶这实际上有效。从技术上讲,forceUpdate正在使用useState's setter 的陈旧版本,但这似乎不会导致错误。

使用这样的旧版本是否安全useState?如果不是,这会导致什么问题?

标签: javascriptreactjsreact-hooks

解决方案


使用这样的旧版本是否安全useState

是的,这就是你this.forceUpdate使用钩子实现的方式。

通常你会看到类似的东西:

// forceRender();
const [, forceRender] = useReducer((p) => !p, false);

它甚至用于react-redux源代码


推荐阅读