理解 React Hooks 心智模型:必须按顺序、不能在条件语句中调用的规则
<h1 id="heading1">前言</h1><p>自从 React 推出 hooks 的 API 后,相信大家对新 API 都很喜欢,但是它对你如何使用它会有一些奇怪的限制。比如,React 官网介绍了 Hooks 的这样一个限制:</p>
<blockquote>
<p>不要在循环,条件或嵌套函数中调用 Hook, 确保总是在你的 React 函数的最顶层以及任何 return 之前调用他们。遵守这条规则,你就能确保 Hook 在每一次渲染中都按照同样的顺序被调用。这让 React 能够在多次的 <code>useState</code> 和 <code>useEffect</code> 调用之间保持 hook 状态的正确。</p>
</blockquote>
<h1 id="heading2">useState Hook 的工作原理</h1>
<p>这个限制并不是 React 团队凭空造出来的,的确是由于 React Hooks 的实现设计而不得已为之。</p>
<p>为了让大家有一个更清晰的思维模型,我将用数组来模拟<code>useState</code>的简单实现。</p>
<p>首先让我们通过一个例子来看看 hook 是如何工作的。</p>
<p>我们首先从一个组件开始:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">function RenderFunctionComponent() {
const = useState("Rudi");
const = useState("Yardley");
return (
<Button onClick={() => setFirstName("Fred")}>Fred</Button>
);
}
</pre>
</div>
<p> </p>
<p>useState hook 背后的思想是,你可以使用 hook 函数返回的数组的第二个数组项作为 setter 函数,并且该 setter 将控制由 hook 管理的状态。</p>
<h1 id="heading3">具体实现</h1>
<h3 id="heading4">1)初始化</h3>
<p>创建两个空数组:<code>setters</code> 和 <code>state</code></p>
<p>将 cursor 设置为 0</p>
<p><img src="https://img2020.cnblogs.com/blog/532971/202107/532971-20210729111013758-191510416.png" alt="" loading="lazy"></p>
<h3 id="heading5">2)第一次渲染</h3>
<p>首次运行组件函数。</p>
<p>每次useState()调用,在第一次运行时,都会将一个 setter 函数推送到 setters 数组上,然后将一些状态推送到 state 数组上。</p>
<p><img src="https://img2020.cnblogs.com/blog/532971/202107/532971-20210729111040565-1891855337.png" alt="" loading="lazy"></p>
<h3 id="heading6">3)后续渲染</h3>
<p>每次后续渲染都会重置 cursor,并且仅从每个数组中读取这些值。</p>
<p><img src="https://img2020.cnblogs.com/blog/532971/202107/532971-20210729111057882-1329150053.png" alt="" loading="lazy"></p>
<h3 id="heading7">4)事件处理</h3>
<p>每个 setter 都有对其 cursor 的引用,因此通过触发对 setter 的调用,setter 它将更改状态数组中该位置的状态值。</p>
<p><img src="https://img2020.cnblogs.com/blog/532971/202107/532971-20210729111131036-1171682237.png" alt="" loading="lazy"></p>
<h3 id="heading8">简单代码实现</h3>
<p>下面通过一段简单的代码示例来演示该实现。</p>
<p>注意:这并不是 React 的底层实现,但对于我们理解 react hook 的<span class="abbreviate-word" data-word-id="53156824">心智模型非常有帮助。</span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">const state = [];
const setters = [];
let cursor = 0;
function createSetter(cursor) {
return function setterWithCursor(newVal) {
state = newVal;
};
}
export function useState(initVal) {
if (state === undefined && setters === undefined) {
state.push(initVal);
setters.push(createSetter(cursor));
}
const setter = setters;
const value = state;
cursor++;
return ;
}
function RenderFunctionComponent() {
const = useState('Rudi'); // cursor: 0
const = useState('Yardley'); // cursor: 1
return (
<div>
<button onClick={() => setFirstName('Richard')}>Richard</button>
<button onClick={() => setLastName('Fred')}>Fred</button>
</div>
);
}
function MyComponent() {
cursor = 0; // resetting the cursor
return <RenderFunctionComponent />; // render
}
console.log(state); // Pre-render: []
MyComponent();
console.log(state); // First-render: ['Rudi', 'Yardley']
MyComponent();
console.log(state); // Subsequent-render: ['Rudi', 'Yardley']
// click the 'Richard' button
console.log(state); // After-click: ['Richard', 'Yardley']</pre>
</div>
<h1 id="heading9">为什么顺序很重要</h1>
<p>现在,如果我们根据某些外部因素甚至组件状态更改渲染周期的钩子顺序会发生什么?</p>
<p>让我们做 React 团队说你不应该做的事情:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">let firstRender = true;
function RenderFunctionComponent() {
let initName;
if(firstRender){
= useState("Rudi");
firstRender = false;
}
const = useState(initName);
const = useState("Yardley");
return (
<Button onClick={() => setFirstName("Fred")}>Fred</Button>
);
} </pre>
</div>
<p>这里我们有<code>useState</code>的一个条件调用。让我们看看这对系统造成的破坏。</p>
<h3 id="heading10">Bad Component 第一次渲染</h3>
<p><img src="https://img2020.cnblogs.com/blog/532971/202107/532971-20210729111310884-1555363583.png" alt="" loading="lazy"></p>
<p>我们的实例变量<code>firstName</code>和<code>lastName</code>包含正确的数据,但让我们看看第二次渲染会发生什么:</p>
<h3 id="heading11">Bad Component 第二次渲染</h3>
<p><img src="https://img2020.cnblogs.com/blog/532971/202107/532971-20210729111330977-325690002.png" alt="" loading="lazy"></p>
<p>现在,<code>firstName</code>和<code>lastName</code>发生了错位,我们的状态存储变得不一致了。这就是为什么保持正确顺序的重要性。</p>
<h1 id="heading12">总结:</h1>
<p>通过对 useState 的简单实现来理解 react hooks 的幕后实现逻辑。考虑将状态作为一组数组存在的模型,那么我们不该违反其对应的使用规则。</p><br><br>
来源:https://www.cnblogs.com/fengyuqing/p/15074207.html
頁:
[1]