reducer封装:
import React, { useReducer, useContext } from 'react';
const initState = {
count: 0,
count1: 0,
count2: [],
}
const myContext = React.createContext();
const initialState = () => {
return { ...initState }
};
const reducer = (state, action) => {
return { ...state, ...action }
};
const ContextProvider = props => {
const [ state, dispatch ] = useReducer(reducer, {}, initialState);
return (
<myContext.Provider value={{ state, dispatch }}>
{props.children}
</myContext.Provider>
);
};
const useSelfState = () => {
const contextValue = useContext(myContext);
return contextValue;
};
export { ContextProvider, useSelfState };
index.js
import React from 'react';
import { ContextProvider } from './reducer';
import Counter from './Counter';
const App = () => {
return (
<div className="App">
<ContextProvider>
<Counter />
</ContextProvider>
</div>
);
};
export default App
child.js
import React from 'react';
import { useSelfState } from './reducer';
function Counter() {
const { state, dispatch } = useSelfState();
console.log('count2', count2)
return (
<div>
Counter Count: {state.count}
<button onClick={() => dispatch({ count2: [ 1, 2, 3 ] })}>Reset</button>
</div>
);
}
export default Counter;