Skip to content

Commit 3239dac

Browse files
docs(en): merge reactjs.org/main into zh-hans.reactjs.org/main @ 0b9ae66 (#1533)
2 parents 38ec3af + 7f9a665 commit 3239dac

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/content/learn/synchronizing-with-effects.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,33 @@ input { display: block; margin-bottom: 20px; }
598598
599599
下面提供一些常用的 Effect 应用模式。
600600
601+
<Pitfall>
602+
603+
#### Don't use refs to prevent Effects from firing {/*dont-use-refs-to-prevent-effects-from-firing*/}
604+
605+
A common pitfall for preventing Effects firing twice in development is to use a `ref` to prevent the Effect from running more than once. For example, you could "fix" the above bug with a `useRef`:
606+
607+
```js {1,3-4}
608+
const connectionRef = useRef(null);
609+
useEffect(() => {
610+
// 🚩 This wont fix the bug!!!
611+
if (!connectionRef.current) {
612+
connectionRef.current = createConnection();
613+
connectionRef.current.connect();
614+
}
615+
}, []);
616+
```
617+
618+
This makes it so you only see `"✅ Connecting..."` once in development, but it doesn't fix the bug.
619+
620+
When the user navigates away, the connection still isn't closed and when they navigate back, a new connection is created. As the user navigates across the app, the connections would keep piling up, the same as it would before the "fix".
621+
622+
To fix the bug, it is not enough to just make the Effect run once. The effect needs to work after re-mounting, which means the connection needs to be cleaned up like in the solution above.
623+
624+
See the examples below for how to handle common patterns.
625+
626+
</Pitfall>
627+
601628
### 控制非 React 组件 {/*controlling-non-react-widgets*/}
602629
603630
有时需要添加不是使用 React 编写的 UI 小部件。例如,假设你要向页面添加地图组件,并且它有一个 `setZoomLevel()` 方法,你希望调整缩放级别(zoom level)并与 React 代码中的 `zoomLevel` state 变量保持同步。Effect 看起来应该与下面类似:

0 commit comments

Comments
 (0)