我为我的Appcontainer创建了一个包装器,以便我可以随时访问我的GlobalState。
const App: () => React$Node = () => {
return (
<>
<GlobalState>
<Appcontainer />
</GlobalState>
</>
);
};
export default App;
我想将 GlobalState 包装器内的大部分逻辑分离到一个单独的文件中。 全局状态电流如下所示:
import React, {useReducer, useEffect} from 'react';
import MainContext from './MainContext';
const GlobalState: props => React$Node = props => {
let updatedState = 0;
const mainReducer = (state, action) => {
switch (action.type) {
case 'add':
console.log('show me the state', state);
updatedState = state.count + action.payload;
return {...state, count: updatedState};
case 'subtract':
updatedState = state.count - action.payload;
return {...state, count: updatedState};
default:
return state;
}
};
const [state, dispatch] = useReducer(mainReducer, {count: 0});
const addDigit = () => {
dispatch({type: 'add', payload: 1});
};
const subtractDigit = () => {
dispatch({type: 'subtract', payload: 1});
};
useEffect(() => {
console.log('show me the state inside useEffect', state);
}, [state]);
return (
<MainContext.Provider
value={{
addDigit: addDigit,
subtractDigit: subtractDigit,
updatedState: updatedState,
}}>
{props.children}
</MainContext.Provider>
);
};
export default GlobalState;
对于我来说,将mainReducer放入reducer.js文件中并将我的两个函数放入它们自己的操作.js文件中的最佳方法是什么?
New GlobalState
import React, {useReducer, useEffect} from 'react';
import {mainReducer, ADD_NUMBER, SUBTRACT_NUMBER} from './reducers';
import MainContext from './MainContext';
/*userReducer is calleed so because it follows that same API as .reduce*/
const initialState = {
count: 0,
};
const GlobalState: props => React$Node = props => {
const [state, dispatch] = useReducer(mainReducer, initialState);
const addDigit = () => {
dispatch({type: ADD_NUMBER, payload: 1});
};
const subtractDigit = () => {
dispatch({type: SUBTRACT_NUMBER, payload: 1});
};
useEffect(() => {
// console.log('show me the state inside useEffect', state);
}, [state]);
return (
<MainContext.Provider
value={{
initialState: initialState,
addDigit: addDigit,
subtractDigit: subtractDigit,
updatedState: state.count,
}}>
{props.children}
</MainContext.Provider>
);
};
export default GlobalState;
化简器.js文件
export const ADD_NUMBER = 'ADD_NUMBER';
export const SUBTRACT_NUMBER = 'SUBTRACT_NUMBER';
const addDigit = (state, payload) => {
const updatedStateValue = state.count;
return {
count: updatedStateValue + 1,
};
};
const subtractDigit = (state, payload) => {
const updatedStateValue = state.count;
return {
count: updatedStateValue - payload,
};
};
export const mainReducer = (state, action) => {
switch (action.type) {
case 'ADD_NUMBER':
return addDigit(state, 1);
case 'SUBTRACT_NUMBER':
return subtractDigit(state, 1);
default:
return state;
}
};