我正在研究React Hooks,使用React Reducer时遇到了一个问题。
直接在状态中为相应状态定义过滤器功能是一种好方法吗?还是破坏了心理编程模型?
import ...
export const ExpensesContext = createContext([]);
const initialState = {
Expenses: [],
// ?
GetExpensesFromCategory(category: string) {
return this.Expenses.filter(i => i.Category === category)
}
};
function reducer(state, action) {
switch (action.type) {
case "update":
return {...state, ...action.payload};
case "delete":
return {};
}
return state;
}
const ExpensesStore = ({children}) => {
const [state, dispatch] = useReducer(reducer, initialState);
const [userState] = useContext(UserContext);
useEffect(() => {
// some behaviour
}, [userState]);
return (
<ExpensesContext.Provider value={[state, dispatch]}>
{children}
</ExpensesContext.Provider>
)
};
export default ExpensesStore;