检查更新了 useEffect 中的哪个依赖项

Check which dependency in useEffect was updated

我有这个 useEffect 钩子:

useEffect(() => {
  setTop(t => t + (controller.position.y * tileSize))
  setLeft(l => l + (controller.position.x * tileSize))
}, [controller.position])

我希望它仅在 position 发生变化时才进行加法运算。如果 tileSize 发生变化,我只想让它进行乘法运算。

我试着把它分成两个 useEffect 但后来我收到了 React Hook useEffect has missing dependencies 警告:

useEffect(() => {
    setTop(t => t + (controller.position.y * spriteSize))
    setLeft(l => l + (controller.position.x * spriteSize))
}, [controller.position])

useEffect(() => {
    setTop((controller.position.y * spriteSize))
    setLeft((controller.position.x * spriteSize))
}, [spriteSize])

这种情况下的最佳做法是什么?

编辑:

一个可重现的例子:

const [tileSize, setTileSize] = useState(0)
const controller = {
    position: {
        x: 0,
        y: 0
    }
}
useEffect(() => {
    setTop(t => t + (controller.position.y * tileSize))
    setLeft(l => l + (controller.position.x * tileSize))
}, [controller.position])

useEffect(() => {
    setTop((controller.position.y * tileSize))
    setLeft((controller.position.x * tileSize))
}, [tileSize])

const asdf = () => {
    setTileSize(150)
}

return (
    <div onClick={() => asdf()}>click me</div>
)

警告信息:

Line 31: React Hook useEffect has a missing dependency: 'tileSize'. Either include it or remove the dependency array. You can also replace multiple useState variables with useReducer if 'setTop' needs the current value of 'tileSize' react-hooks/exhaustive-deps

Line 36: React Hook useEffect has missing dependencies: 'controller.position.x' and 'controller.position.y'. Either include them or remove the dependency array react-hooks/exhaustive-deps Line 46: Unreachable code no-unreachable

方法有很多种,您应该选择最适合您的用例的一种。

  1. 如警告所示,替换为useReducer

React Hook useEffect has a missing dependency: 'tileSize'. Either include it or remove the dependency array. You can also replace multiple useState variables with useReducer if 'setTop' needs the current value of 'tileSize'. (react-hooks/exhaustive-deps)

const STATE = {
  ADDITION: 'addition',
  MULTIPLICATION: 'multiplication'
};

function reducer(state, action) {
  switch (action.type) {
    case STATE.ADDITION:
      return {
        ...state,
        position: action.position,
        top: state.top + action.position * state.spriteSize
      };
    case STATE.MULTIPLICATION:
      return {
        ...state,
        spriteSize: action.spriteSize,
        top: state.position * action.spriteSize
      };
    default:
      throw new Error();
  }
}

function Controller({ position, spriteSize }) {
  const [state, dispatch] = useReducer(reducer, {
    top: 0,
    position,
    spriteSize
  });

  useEffect(() => {
    dispatch({ type: STATE.ADDITION, position });
  }, [position]);

  useEffect(() => {
    dispatch({ type: STATE.MULTIPLICATION, spriteSize });
  }, [spriteSize]);

  return <FlexBox>{state.top}</FlexBox>;
}
  1. 您可以使用引用 useRef 并与旧值进行比较
  2. 如果您知道自己在做什么,只需禁用 lint 警告即可。