如何在 React Hooks useEffect 上比较 oldValues 和 newValues? [英] How to compare oldValues and newValues on React Hooks useEffect?

查看:69
本文介绍了如何在 React Hooks useEffect 上比较 oldValues 和 newValues?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 3 个输入:rate、sendAmount 和 receiveAmount.我把这 3 个输入放在 useEffect diffing 参数上.规则是:

Let's say I have 3 inputs: rate, sendAmount, and receiveAmount. I put that 3 inputs on useEffect diffing params. The rules are:

  • 如果sendAmount改变了,我计算receiveAmount = sendAmount * rate
  • 如果receiveAmount改变,我计算sendAmount = receiveAmount/rate
  • 如果汇率改变,当 sendAmount > 时,我计算 receiveAmount = sendAmount * rate0 或者当 receiveAmount > 时我计算 sendAmount = receiveAmount/rate0

这是用于演示问题的代码和框 https://codesandbox.io/s/pkl6vn7x6j.

Here is the codesandbox https://codesandbox.io/s/pkl6vn7x6j to demonstrate the problem.

有没有办法像在 componentDidUpdate 上一样比较 oldValuesnewValues 而不是为这种情况制作 3 个处理程序?

Is there a way to compare the oldValues and newValues like on componentDidUpdate instead of making 3 handlers for this case?

谢谢

这是我使用 usePrevious 的最终解决方案https://codesandbox.io/s/30n01w2r06

Here is my final solution with usePrevious https://codesandbox.io/s/30n01w2r06

在这种情况下,我不能使用多个 useEffect,因为每次更改都会导致相同的网络调用.这就是为什么我也使用 changeCount 来跟踪更改的原因.这个 changeCount 也有助于仅从本地跟踪更改,因此我可以防止由于来自服务器的更改而导致不必要的网络调用.

In this case, I cannot use multiple useEffect because each change is leading to the same network call. That's why I also use changeCount to track the change too. This changeCount also helpful to track changes from local only, so I can prevent unnecessary network call because of changes from the server.

推荐答案

您可以编写自定义钩子来为您提供previous props 使用 useRef

You can write a custom hook to provide you a previous props using useRef

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

然后在useEffect

const Component = (props) => {
    const {receiveAmount, sendAmount } = props
    const prevAmount = usePrevious({receiveAmount, sendAmount});
    useEffect(() => {
        if(prevAmount.receiveAmount !== receiveAmount) {

         // process here
        }
        if(prevAmount.sendAmount !== sendAmount) {

         // process here
        }
    }, [receiveAmount, sendAmount])
}

但是,如果您为要单独处理它们的每个更改 id 分别使用两个 useEffect ,它会更清晰,可能更好,更清晰易读

However its clearer and probably better and clearer to read and understand if you use two useEffect separately for each change id you want to process them separately

这篇关于如何在 React Hooks useEffect 上比较 oldValues 和 newValues?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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