在useEffect中反应钩子updateState

时间:2020-03-12 10:34:08

标签: reactjs react-hooks

我想在16.0_xxxxx_Config内更新组件的状态,但是仅当对象已更改时才比较并更新状态。

我该怎么做?

这是我当前的代码:

useEffect

2 个答案:

答案 0 :(得分:0)

udeDeepCompare.js

import { useRef, useEffect } from "react";
import _ from "lodash";

function useDeepEffect(fn, deps) {
  const isFirst = useRef(true);
  const prevDeps = useRef(deps);

  useEffect(() => {
    const isSame = prevDeps.current.every((obj, index) =>
      _.isEqual(obj, deps[index])
    );

    if (isFirst.current || !isSame) {
      fn();
    }

    isFirst.current = false;
    prevDeps.current = deps;
  }, deps);
}

export default useDeepEffect;

Features.js

useEffect(() => {
    fetchProductFeature();
  }, [fetchProductFeature]);

  useDeepEffect(() => {
    console.log("State changed!");
    let features =
      productFeature.data &&
      productFeature.data.map(feature => ({
        label: feature,
        value: false
      }));
    setFeatures(features);
  }, [productFeature.data]);

答案 1 :(得分:0)

您可以在设置状态之前比较以前的状态,请参见以下示例

    useEffect(() => {
      const fetchAndUpdateState = async () => {
        const data = await api.fetchData();
        setFeatures((prevState) => {
          if(deepCompare(prevState,data) {
            return data;
          }
        })
      }
      fetchAndUpdateState();
    }, [])

此外,我建议您使用lodash.isEqual进行深度比较https://lodash.com/docs/#isEqual