学习 React:State
在学习 React 的过程中,要说什么最重要,毋庸置疑便是 State。State 是 React 中最重要的概念,State 是 一个 React 应用的灵魂,我们使用 React 构建的用户界面便是对 State 的外在映射。
ui = f(state)
在 React 的模型中,我们要更新用户界面,必须通过触发 State 的变更来引起。当 State 发生变化时,React 会重新渲染一次,决定我们的用户界面是否更新。State 的变更,我们是通过 useState
这个内置 Hooks 来实现的。
实现自己的 useState
let componentHooks = [];
let currentHookIndex = 0;
// How useState works inside React (simplified).
function useState(initialState) {
let pair = componentHooks[currentHookIndex];
if (pair) {
// This is not the first render,
// so the state pair already exists.
// Return it and prepare for next Hook call.
currentHookIndex++;
return pair;
}
// This is the first time we're rendering,
// so create a state pair and store it.
pair = [initialState, setState];
function setState(nextState) {
// When the user requests a state change,
// put the new value into the pair.
pair[0] = nextState;
updateDOM();
}
// Store the pair for future renders
// and prepare for the next Hook call.
componentHooks[currentHookIndex] = pair;
currentHookIndex++;
return pair;
}
实现 useState 的批处理
export function getFinalState(baseState, queue) {
let finalState = baseState;
for (let update of queue) {
if (typeof update === 'function') {
// Apply the updater function.
finalState = update(finalState);
} else {
// Replace the next state.
finalState = update;
}
}
return finalState;
}
实现 useRef
function useRef(initialValue) {
const [ref, unused] = useState({ current: initialValue });
return ref;
}
实现 useReducer
import { useState } from 'react';
export function useReducer(reducer, initialState) {
const [state, setState] = useState(initialState);
function dispatch(action) {
const nextState = reducer(state, action);
setState(nextState);
}
return [state, dispatch];
}