我正在开发一个React Native应用程序,在基于Redux状态的条件渲染方面遇到了一些问题,我使用useSelector
获取该状态。
我尝试过使用和不使用下面的useEffect
(因此直接返回组件而不是设置状态(,但当状态更新时,从useSelector
返回的变量似乎不会改变。由于状态一开始是加载的,所以我最终进入了最新的else if
,并被困在那里。然后我必须刷新应用程序以获得实际值并到达所需的屏幕
const ContainerA = ({ navigation }) => {
const {
loginSuccess,
loginLoading,
accountType,
permissionsSuccess,
permissionsLoading,
} = useSelector((state) => state.accountInfo);
const [toRender, setToRender] = useState(null);
useEffect(() => {
if (loginSuccess) {
if (loginSuccess.success === 1 && accountType === 3) {
console.log('[Container] case 1');
setToRender(<PageA navigation={navigation} />);
// return <PageA navigation={navigation} />;
// return;
} else if (
(loginSuccess.success === 1 &&
(accountType === 1 || accountType === 2)) || (loginSuccess.success === 0)
) {
console.log('[Container] case 2');
navigation.navigate(SCREENS.CONTROL_PANEL);
}
} else if (loginLoading || permissionsLoading) {
console.log('[Container] case 4');
setToRender(<LoadingPage />);
// return <LoadingPage />;
// return;
}
}, [
loginSucess,
loginLoading,
accountType,
navigation,
permissionSuccess,
permissionsLoading,
]);
return toRender;
};
export default ContainerA;
Redux减速器:
case 'loginInit':
return updateState(state, {
loginLoading: true,
loginSuccess: null,
loginFail: null,
});
case 'loginSuccess':
return updateState(state, {
loginLoading: false,
loginSuccess: action.success,
});
case 'loginFail':
return updateState(state, {
loginLoading: false,
loginFail: action.error,
});
case 'permissionsInit':
return updateState(state, {
permissionsLoading: true,
accountType: null,
permissionsSuccess: null,
permissionsFail: null,
});
case 'permissionsSuccess':
return updateState(state, {
permissionsLoading: false,
permissionsSuccess: action.success,
accountType: action.success.success
? action.success.success
: action.success.errors,
});
case 'permissionsFail':
return updateState(state, {
permissionsLoading: false,
permissionsFail: action.error,
});
updateState函数:
export const updateState = (state, updatedProps) => ({
...state,
...updatedProps,
});
似乎我在一个不应该得到任何成功响应的地方执行进行检查的函数。我通过在导航器中调用那些我确信有令牌的函数来修复它,因为这些调用需要令牌(并且在没有令牌的情况下不会执行实际的API调用(。ContainerA
中剩余的代码为:
const {
firstLoginSuccess,
firstLoginLoading,
accountType,
permissionsSuccess,
permissionsLoading,
} = useSelector((state) => state.accountInfo);
if (firstLoginSuccess) {
if (firstLoginSuccess.success === 1 && accountType === 3) {
return <FirstTimeLoginPage navigation={navigation} />;
} else if (
(firstLoginSuccess.success === 1 &&
(accountType === 1 || accountType === 2)) ||
firstLoginSuccess.success === 0
) {
navigation.navigate(SCREENS.CONTROL_PANEL);
}
} else if (firstLoginLoading || permissionsLoading) {
console.log('[FirstTimeLoginContainer] case 4');
}
return <LoadingPage />;