【发布时间】:2020-07-20 09:31:49
【问题描述】:
我在我的 react 本机应用程序上使用 React Navigation 并遵循其身份验证流程。
app.js 将根据称为 userProfile 的用户身份验证状态呈现身份验证屏幕或主屏幕。
userProfile 将通过称为 userContext 的 React 上下文从 App 组件传递到子组件,并且一些调度函数也将被称为 authContext 传递。
const App: () => React$Node = () => {
const [state, dispatch] = React.useReducer(
(prevState, action) => {
switch (action.type) {
case SIGN_IN:
return {
...prevState,
userProfile: action.userProfile,
};
case SIGN_OUT:
return {
...prevState,
userProfile: null,
};
}
},
{
isLoading: true,
userProfile: null,
}
)
React.useEffect(() => {
isMountedRef.current = true;
return () => (isMountedRef.current = false);
}, []);
const authContext = React.useMemo(
() => ({
signIn: async userProfile => {
try {
await AsyncStorage.setItem('userProfile', JSON.stringify(userProfile))
dispatch({ type: SIGN_IN, userProfile })
} catch (error) {
console.log(error)
}
},
signOut: async () => {
try {
await AsyncStorage.removeItem('userProfile');
dispatch({ type: SIGN_OUT })
} catch (error) {
console.log(error)
}
}
}),
[]
);
return (
<AuthContext.Provider value={{authContext, userContext: state.userProfile}}>
<NavigationContainer ref={navigationRef}>
<Stack.Navigator>
{console.log('app render: ', state.userProfile)}
{
state.userProfile == null ?
(<Stack.Screen name="AuthContainer" component={AuthContainer} options={{ headerShown: false }} />) :
(<Stack.Screen name="MainContainer" component={MainContainer} options={{ headerShown: false }} />)
}
</Stack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
);
};
在上面代码中主屏幕或 MainContainer 下的嵌套子组件 ProfileScreen 之一中,我正在尝试使用 userContext 在屏幕上显示用户信息,并且注销按钮正在使用调度注销功能进行更新App 组件中的用户身份验证状态为 null。
function ProfileScreen() {
const { authContext, userContext } = React.useContext(AuthContext)
console.log('profile render: ', userContext)
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Hello {userContext.username}!</Text>
<Text>Profile Screen</Text>
<Button
title="Sign Out"
onPress={() => authContext.signOut()}
/>
</View>
);
}
export default ProfileScreen;
调度退出功能后,我希望应用导航到身份验证屏幕 AuthContainer 以要求用户再次登录,因为此时我在 App 组件中的 userProfile 状态应该为空。但是,App 组件仍在尝试呈现抛出错误 userContext is null 的 ProfileScreen。
从我的日志中,我在 ProfileScreen 中调度退出功能后,它显示
app render: null ---> App re-render
profile render: null ---> profileScreen re-render
profile render: null ---> profileScreen re-render
auth container ---> finally start rendering Auth Screen
然后立即抛出 userContext is null 错误
谁能帮助我理解为什么 App 组件在 userProfile 状态为空时尝试渲染 profileScreen?为什么 profileScreen 会重新渲染两次?
谢谢你
【问题讨论】:
标签: javascript reactjs react-native react-navigation