React 在 useEffect 中重写 componentWillReceiveProps

Chr*_*ris 2 reactjs react-hooks

所以我正在重新编写一个带有钩子的组件,我遇到了一个有趣的挑战,我需要模仿一些componentWillReceiveProps带有useEffect钩子的旧行为。

我的旧代码如下:

componentWillReceiveProps(nextProps: Props) {

  const prevLateVal = get(`lateMinutes[${bookingId}].value`, this.props);
  const nextLateVal = get(`lateMinutes[${bookingId}].value`, nextProps); //see here, 
//we use next props

  if (typeof nextLateVal !== 'undefined' && prevLateVal !== nextLateVal) {
    client.connect(bookingId, nextLateVal === null ? 0 : nextLateVal);

  }
}
Run Code Online (Sandbox Code Playgroud)

你看,我正在启动一个const基于 nextProps,然后在if语句中我根据 nextVal做一些检查,现在,我知道我们可以指定第二个参数useEffect来运行它,只有当道具改变时,但那些呢检查,我怎样才能实现类似的东西nextProps

Ava*_*ika 5

您可以创建自定义钩子:

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.prevLateVal = value;
  });
  return ref.prevLateVal;
}
Run Code Online (Sandbox Code Playgroud)

并将其用于 useEffect()

const Component = (props) => {
    const currentLateValue = get(`lateMinutes[${bookingId}].value`, props)
    const prevLateVal = usePrevious(currentLateValue);
    useEffect(() => {
        if(prevLateVal !== currentLateValue) {
         // process here
        }
    }, [currentLateValue]) // This will be executed only if currentLateValue changes.
}
Run Code Online (Sandbox Code Playgroud)