我正在开发一个 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 reducer:
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 />;