useReducer
useReducer 是一個(gè)可以讓你向組件中添加 reducer 的 Hook
const [state, dispatch] = useReducer(reducer, initialArg, init?)
基本用法
const reducer = (state, action) => {
...
}
const MyComponent = () => {
const [state, dispatch] = useReducer(reducer, {age: 42})
const handleClick = () => {
dispatch({type:'increase'})
}
...
}
比 useState 多了一個(gè)處理函數(shù),該函數(shù)可以根據(jù)不同的分發(fā)狀態(tài)來(lái)對(duì)應(yīng)的改變狀態(tài)
注意:state 不可修改 不能這樣寫, reducer 函數(shù)應(yīng)當(dāng)返回一個(gè)新對(duì)象
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// ?? Don't mutate an object in state like this:
state.age = state.age + 1;
return state;
}
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// ? Instead, return a new object
return {
...state,
age: state.age + 1
};
}
不要重新執(zhí)行初始函數(shù) 第一種寫法會(huì)導(dǎo)致每次渲染時(shí)候都調(diào)用 createInitialState 函數(shù) 造成性能浪費(fèi)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-545783.html
function createInitialState(username) {
// ...
}
// ?
function TodoList({ username }) {
const [state, dispatch] = useReducer(reducer, createInitialState(username));
// ?
function TodoList({ username }) {
const [state, dispatch] = useReducer(reducer, username, createInitialState);
// ...
dispatch 后如何使用最新的狀態(tài)值
調(diào)用 dispatch 函數(shù)不會(huì)更改運(yùn)行代碼中的狀態(tài) ,使用最新的狀態(tài)值應(yīng)該是這樣寫文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-545783.html
function handleClick() {
console.log(state.age); // 42
dispatch({ type: 'incremented_age' }); // Request a re-render with 43
console.log(state.age); // Still 42!
setTimeout(() => {
console.log(state.age); // Also 42!
}, 5000);
}
const action = { type: 'incremented_age' };
dispatch(action);
const nextState = reducer(state, action);
console.log(state); // { age: 42 }
console.log(nextState); // { age: 43 }
參考
- https://react.dev/reference/react/useReducer
到了這里,關(guān)于React 新版官方文檔 (一) useReducer 用法詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!