在 useEffect 中使用 setState 会导致测试中出现最大更新部门超出错误

问题描述 投票:0回答:1

我有一个函数,它获取组件中的 props 值并将其展平为组件可以使用的形式。每次 props 值发生变化时都需要发生这种情况。我将 setState 放入 useEffect 中,并将 props 值作为依赖项之一,但 Jest 测试不喜欢这样。这基本上就是我的代码的样子。

const myComponent = (props) => {

   const [mappedThing, setMappedThing] = useState(mapThing(props.thing));

   useEffect(() => {
      setMappedThing(mapThing(props.thing));
   }, [props.thing]);

   const mapThing => (notFlatStructure) => {
      // Do stuff here to flatten structure.
      return flattendStructure;
   };

   return (
      // Component that uses flattened thing.
   );
};

是否有一种标准方法可以在每次 props 更改时设置上面的mappedThing,而不使用 useEffect?每当我拿走 useEffect 时,组件就会停止更新。

javascript reactjs react-hooks
1个回答
0
投票

你不需要状态,当你想改变 prop 的值时,只需使用

const
:

// Declare the transform function out of the component if it doesn't depend on props/state
const mapThing => (notFlatStructure) => {
  // Do stuff here to flatten structure.
  return flattendStructure;
};

const myComponent = (props) => {
  const mappedThing = mapThing(props.thing);

  return (
    // Component that uses flattened thing.
  );
};

如果计算量很大,请用

useMemo
:

括起来
const myComponent = (props) => {
  const mappedThing = useMemo(() => mapThing(props.thing), [props.thing]);

  return (
    // Component that uses flattened thing.
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.