关于新提出的React Effect Hook ;
Effect
Hook (useEffect()
) 有哪些优点和用例?为什么它会更可取?它与
componentDidMount/componentDidUpdate/componentWillUnmount
(性能/可读性)有何不同?
文档指出:
Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase).
但我认为将这些行为放在生命周期方法(如 componentDidUpdate 等)而不是渲染方法中已经是常识。
还有提到:
The function passed to useEffect will run after the render is committed to the screen.
但这不正是 componentDidMount
和 componentDidUpdate
所做的吗?
最佳答案
-
What are the advantages and use cases of the
Effect
hook (useEffect()
)?优势
主要是,钩子(Hook)通常可以提取和重用跨多个组件通用的有状态逻辑,而无需高阶组件或渲染 Prop 的负担。
第二个好处(尤其是 Effect hooks)是避免了如果在
componentDidUpdate
中没有正确处理依赖于状态的副作用可能会出现的错误(因为 Effect hooks 确保这些副作用在每个渲染器上设置和拆除)。另请参阅下文详述的性能和可读性优势。
用例
任何使用生命周期方法实现有状态逻辑的组件——Effect Hook 是一种“更好的方式”。
-
Why would it be preferable & how does it differ over
componentDidMount
/componentDidUpdate
/componentWillUnmount
(performance/readability)?为什么它更可取
由于上文和下文详述的优点。
它与生命周期方法有何不同
性能
效果 Hook —
- 感觉比生命周期方法响应更快,因为它们不会阻止浏览器更新屏幕;
- 但是会在每个渲染上设置和拆除副作用,这可能很昂贵......
- …因此可以优化为完全跳过,除非已更新特定状态。
可读性
效果 Hook 导致:
更简单且更易于维护的组件,因为能够将以前必须在同一组生命周期方法中表达的不相关行为拆分为每个此类行为的单个 Hook - 例如:
componentDidMount() { prepareBehaviourOne(); prepareBehaviourTwo(); } componentDidUnmount() { releaseBehaviourOne(); releaseBehaviourTwo(); }
变成:
useEffect(() => { prepareBehaviourOne(); return releaseBehaviourOne; }); useEffect(() => { prepareBehaviourTwo(); return releaseBehaviourTwo; });
请注意,与
BehaviourOne
相关的代码现在与与BehaviourTwo
相关的代码明显分开,而之前它混合在每个生命周期方法中。样板文件更少,因为消除了在多个生命周期方法中重复相同代码的需要(例如在
componentDidMount
和componentDidUpdate
之间很常见)—例如:componentDidMount() { doStuff(); } componentDidUpdate() { doStuff(); }
变成:
useEffect(doStuff); // you'll probably use an arrow function in reality
关于javascript - react Hook : What/Why `useEffect` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051465/