Skip to content

Commit bb7b58d

Browse files
committed
add diffValues.md
1 parent e1e9615 commit bb7b58d

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@
8787
8888
1. [React 中, state 和 props 的区别是什么?应该怎么使用?](./contents/react/stateVsProps.md)
8989
2. [React Context 和 React Redux 的区别是什么?应该怎么使用?](./contents/react/context.md)
90-
90+
3. [React Hooks 中,如何在 useEffect 里比较 oldValues 和 newValues ?](./contents/react/diffValues.md)
91+
9192
- todo ...
9293

9394
> Node.js

contents/react/diffValues.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
## 问题:React Hooks 中,如何在 useEffect 里比较 oldValues 和 newValues ?
2+
3+
我有 3 个根据输入并进行值变化的数据:`rate``sendAmount``receiveAmount`
4+
5+
现在我把这 3 个数据放在了 3 个 `useEffect` 的不同参数上,有以下规则:
6+
7+
- 如果 `sendAmount` 改变了,计算 `receiveAmount = sendAmount * rate`
8+
- 如果 `receiveAmount` 改变了,计算 `sendAmount = receiveAmount / rate`
9+
- 如果 `rate` 改变了,当 `sendAmount > 0` 时,计算`receiveAmount = sendAmount * rate`,或者当 `receiveAmount > 0` 时,计算 `sendAmount = receiveAmount / rate`
10+
11+
是否有办法像在 `componentDidUpdate` 上那样直接比较 `oldValues``newValues`,而不是现在这样为这种情况做 3 个规则判断?
12+
13+
## 答案
14+
15+
你可以写一个自定义 `hook`,使用 `useRef` 可以获得之前的数据 ([previous props](https://zh-hans.reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state))
16+
17+
```js
18+
function usePrevious(value) {
19+
const ref = useRef();
20+
useEffect(() => {
21+
ref.current = value;
22+
});
23+
return ref.current;
24+
}
25+
```
26+
27+
然后在 `useEffect` 中使用:
28+
29+
```js
30+
const Component = (props) => {
31+
const {receiveAmount, sendAmount } = props
32+
const prevAmount = usePrevious({receiveAmount, sendAmount});
33+
useEffect(() => {
34+
if(prevAmount.receiveAmount !== receiveAmount) {
35+
36+
// process here
37+
}
38+
if(prevAmount.sendAmount !== sendAmount) {
39+
40+
// process here
41+
}
42+
}, [receiveAmount, sendAmount])
43+
}
44+
```
45+
46+
如果你为每个变化的 `id` 分别使用不同的 `useEffect` 来进行处理,逻辑会更清楚,这样可能更好,也更容易阅读和理解。
47+
48+
> 问题来源:[https://stackoverflow.com/questions/53446020/how-to-compare-oldvalues-and-newvalues-on-react-hooks-useeffect](https://stackoverflow.com/questions/53446020/how-to-compare-oldvalues-and-newvalues-on-react-hooks-useeffect)

0 commit comments

Comments
 (0)