[英]using useContext with custom hooks vs useContext + useReducer
[英]React useContext & useReducer - Need global state in app, confused about using one vs multiple reducers
我需要在我的应用程序中共享信息片段,例如用户详细信息、头像和应用程序内提醒。 我担心我可能没有以正确的方式使用 useReducer 和 useContext,因为我只是将所有内容订阅到这个 reducer 并将其用作一个巨大的全局状态设置函数。 我应该以不同的方式处理这个问题吗?
const initialState : IStore = { isLoading : true, isSignedIn : false, newUser : false, hero : null, alerts : [] };
const store = createContext<IStore>(initialState);
const { Provider } = store;
const StateProvider : React.FC = ( { children } ) => {
const [state, dispatch] = useReducer((state : IStore, action : IAction) => {
switch(action.type) {
case 'TOGGLE LOADING': {
const { isLoading } = action.payload;
if(typeof isLoading === 'undefined'){
return Object.assign({}, state, { isLoading : !state.isLoading });
}
return Object.assign({}, state, { isLoading });
}
case 'SET EXISTING USER INIT DATA': {
const { user, hero, gameItems, latestBattle, isSignedIn } = action.payload;
return { ...state, ...{ user, hero, gameItems, latestBattle, isSignedIn } };
}
case 'SET ISSIGNEDIN': {
const { isSignedIn } = action.payload;
return { ...state, isSignedIn };
}
case 'SET NEW USER': {
const { newUser } = action.payload;
return { ...state, newUser };
}
case 'SET HERO': {
const { hero } = action.payload;
return { ...state, hero };
}
case 'SET USER': {
const { user } = action.payload;
return { ...state, user };
}
case 'SET ALERTS': {
const { alerts } = action.payload;
return { ...state, alerts : [...alerts] };
}
case 'REMOVE ALERTS': {
const { indiciesForRemoval } = action.payload;
return { ...state, alerts :
state.alerts.filter((alert) => {
return !indiciesForRemoval.includes(alert.index);
})
};
}
default:
throw new Error('In Store default, should not happen.');
};
}, initialState);
return (
<Provider value={{ state, dispatch }}>
{children}
</Provider>
);
};
更多的是代码质量的问题:
如果你只使用一点状态和少量动作,一个减速器就可以了。 您必须注意的一件事是重新渲染触发:每当您的减速器的状态更新时,每个使用该减速器的组件都必须重新渲染。 对于小状态,这不是问题,但是如果你有很多需要state.fieldA
的复杂组件和很多需要state.fieldB
的复杂组件,那么它可能值得拆分。 否则更新fieldA
也会触发所有只对fieldB
感兴趣的组件的重新渲染。 尽管可以进行某些优化以部分抵消这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.