react hook useReducer
使用useReducer 封装计数器的维护逻辑
import React, { useState, useEffect, useReducer } from "react";
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case "inc":
return state + 1;
case "dec":
return state - 1;
case "reset":
return initialState;
default:
return state;
}
};
export default () => {
const [count, dispatch] = useReducer(reducer, initialState);
const [count2, dispatch2] = useReducer(reducer, initialState);
return (
<div>
<div>Count: {count}</div>
<button onClick={() => dispatch("inc")}>inc</button>
<button onClick={() => dispatch("dec")}>dec</button>
<button onClick={() => dispatch("reset")}>reset</button>
<div>Count2: {count2}</div>
<button onClick={() => dispatch2("inc")}>inc</button>
<button onClick={() => dispatch2("dec")}>dec</button>
<button onClick={() => dispatch2("reset")}>reset</button>
</div>
);
};
跨组件修改状态
在根组件使用context传入dispatch, 在子组件调用dispatch函数, 修改数据, 同时在根组件中查看最新的数据
import React, { useState, useEffect, useReducer, useContext } from "react";
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case "inc":
return state + 1;
case "dec":
return state - 1;
case "reset":
return initialState;
default:
return state;
}
};
const A = () => {
const context = useContext(CountContext);
return (
<div>
A<button onClick={() => context.dispatch("inc")}>inc</button>
<B></B>
</div>
);
};
const B = () => {
const context = useContext(CountContext);
return (
<div>
B<button onClick={() => context.dispatch("dec")}>dec</button>
<C></C>
</div>
);
};
const C = () => {
const context = useContext(CountContext);
return (
<div>
C<button onClick={() => context.dispatch("reset")}>reset</button>
</div>
);
};
const Root = () => {
const context = useContext(CountContext);
return (
<div>
Root:{context.count}
<A></A>
</div>
);
};
const CountContext = React.createContext();
export default () => {
const [count, dispatch] = useReducer(reducer, initialState);
return (
<div>
<CountContext.Provider
value={{
count,
dispatch,
}}
>
<Root></Root>
</CountContext.Provider>
</div>
);
};