React 在 useEffect 中重写 componentWillReceiveProps

React 在 useEffect 中重写 componentWillReceiveProps

问题描述:

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

So I am re-writing a component with hooks, and I ran into an interesting challenge, I need to mimick some old behaviour of componentWillReceiveProps with the useEffect hook.

我的旧代码如下:

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);

  }
}

你看,我正在基于 nextProps 启动一个 const,然后在 if 语句中我根据 nextVal 做一些检查,现在,我知道我们可以为 useEffect 指定第二个参数以仅在 prop 更改时运行它,但是那些检查呢,我如何实现类似于 nextProps 的东西?

You see, I am initiating a const based on nextProps, then in the if statement i do a couple checks based on that nextVal, now, I know that we can specify a second argument to useEffect to run it only when a prop changes, but what about those checks, how can i implement something similar to nextProps?

您可以创建自定义钩子:

You can create custom hook:

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.prevLateVal = value;
  });
  return ref.prevLateVal;
}

并在 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.
}