【问题标题】:Clear Ref in useEffect CleanupClear Ref in useEffect Cleanup
【发布时间】:2020-02-20 10:02:26
【问题描述】:

我有一个叫做 useInitial 的钩子定义为


function useInitial(value) {

  const ref = useRef();

  // Store current value in ref

  useEffect(() => {
    ref.current = value;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Return previous value (happens before update in useEffect above)

  return ref.current;
}

我在函数组件中使用它来存储字段的初始值


const Calculator = ({ current_field }) => {
  const previousField = usePrevious(current_field);
  const intialContent = useInitial(current_field.content);
  useEffect(() => {
    calculateTotals();
    if (previousField) {
      console.log({ intialContent });
      console.log(previousField.content);
    }
    return () => {
     //DO something here to clear and reset the value stored in intialContent.
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [current_field]);
  return null;
};

如果 CurrentField 发生变化,我想要新字段的初始值,而不是第一个。

【问题讨论】:

    标签: reactjs react-hooks react-state-management


    【解决方案1】:

    我想通了,找到了解决办法。

    useInitial hook 可以修改为像 inupt 这样的 deps 数组

    function useInitial(value, deps) {
    
      const ref = useRef();
    
      // Store current value in ref
    
      useEffect(() => {
        ref.current = value;
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, deps);
    
      // Return previous value (happens before update in useEffect above)
    
      return ref.current;
    }
    

    然后它的用法可能是在 deps 数组中发送 current_field。

    const Calculator = ({ current_field }) => {
      const previousField = usePrevious(current_field);
      const intialContent = useInitial(current_field.content);
      useEffect(() => {
        calculateTotals();
        if (previousField) {
          console.log({ intialContent });
          console.log(previousField.content);
        }
    
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [current_field]);
      return null;
    };
    

    这将在字段更改后重新触发 useInitial 内部的 useEffect 并存储新字段的初始值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2019-05-20
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多