问题描述
假设我有 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 * rate
0receiveAmount > 时我计算
sendAmount = receiveAmount/rate
0
这是用于演示问题的代码和框 https://codesandbox.io/s/pkl6vn7x6j.
Here is the codesandbox https://codesandbox.io/s/pkl6vn7x6j to demonstrate the problem.
有没有办法像在 componentDidUpdate
上一样比较 oldValues
和 newValues
而不是为这种情况制作 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!