小编典典

在使用中反应重写组件WillReceiveProps

reactjs

所以我重新写带钩的分量,我遇到了一个有趣的挑战,我需要模拟天生的一些老问题componentWillReceivePropsuseEffect困境。

我的旧代码如下:

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

  }
}

您会看到,我正在const基于nextProps 发起一个a ,然后在if语句中我基于nextVal
进行了几次检查,现在,我知道我们可以指定第二个参数以useEffect仅在prop更改时运行它,那检查,我怎样才能实现类似于nextProps


阅读 322

收藏
2020-07-22

共1个答案

小编典典

您可以创建自定义钩子:

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.
}
2020-07-22