React 在 useEffect 中重写 componentWillReceiveProps [英] React re-write componentWillReceiveProps in useEffect

查看:67
本文介绍了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.
}

这篇关于React 在 useEffect 中重写 componentWillReceiveProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆