useReducer
作為 useState
的代替方案,在某些場(chǎng)景下使用更加適合,例如 state 邏輯較復(fù)雜且包含多個(gè)子值,或者下一個(gè) state 依賴于之前的 state 等。
使用 useReducer
還能給那些會(huì)觸發(fā)深更新的組件做性能優(yōu)化,因?yàn)楦附M件可以向自組件傳遞 dispatch 而不是回調(diào)函數(shù)文章來源:http://www.zghlxwxcb.cn/news/detail-609611.html
const [state, dispatch] = useReducer(reducer, initialArg, init);
使用:
import React, { useReducer } from 'react'
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
?初始化 state:
useReducer 初始化 sate 的方式有兩種文章來源地址http://www.zghlxwxcb.cn/news/detail-609611.html
// 方式1
const [state, dispatch] = useReducer(
reducer,
{count: initialCount}
);
// 方式2
function init(initialClunt) {
return {count: initialClunt};
}
const [state, dispatch] = useReducer(reducer, initialCount, init);
到了這里,關(guān)于React的hooks---useReducer的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!