问题
I'm trying to dynamically navigate between stacks via a single fetch from a server, which reads a token from the device, and makes a server request to update isUserExists.
if isUserExists is false, render AuthStack, otherwise render AppStack.
My code:
Example for AuthStack.js
:
import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import { Auth, Registration, Login, VerifyAuth } from "../../screens/auth";
const Stack = createStackNavigator();
const AuthStack = () => {
return (
<Stack.Navigator initialRouteName="Auth">
<Stack.Screen name="Auth" component={Auth} />
<Stack.Screen name="Registration" component={Registration} />
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="VerifyAuth" component={VerifyAuth} />
</Stack.Navigator>
);
};
export default AuthStack;
AppNavigator.js
const AppNavigator = () => {
const dispatch = useDispatch();
const isUserExists = useSelector((state) => state.auth.isUserExists);
const [allowNavigate, setAllowNavigate] = useState(false);
const fetchData = async () => {
const token = await TokensHandler.getTokenFromDevice();
if (token === null) {
dispatch(setIsUserExists(false));
setAllowNavigate(true);
} else
dispatch(isUserExistsByToken(token)).then(() => setAllowNavigate(true));
};
useEffect(() => {
fetchData();
}, []);
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
{allowNavigate ? (
<View>
<ActivityIndicator size="large" />
<StatusBar barStyle="default" />
</View>
) : (
<NavigationContainer>
{isUserExists ? <AppStack /> : <AuthStack />}
</NavigationContainer>
)}
</View>
);
};
export default AppNavigator;
My problem is that the component does not re-renders when isUserExists prop updates after fetch is complete.
How can I handle that?
Am I even doing this right? I feel like I can clean up my code and I just don't know how.
Thanks for the help.
来源:https://stackoverflow.com/questions/62970998/dynamically-navigating-between-stacks-with-react-navigation-5