【发布时间】:2020-11-25 17:08:33
【问题描述】:
我正在用 react native 制作一个小应用程序,它是一个基本的登录工作流程,它使用几个屏幕(登录和主页),根据用户状态显示;在 App.js 中,我有一堆状态用于启用/禁用视图、按钮、显示用户名等。 我在外部组件中有登录屏幕和主屏幕。我想知道(除了使用上下文之外)是否有办法让这些状态(和功能)可用于子屏幕
这是我的代码的一部分:
App.js
export default function App() {
const [isLoading, setIsLoading] = useState(true);
const [isLogged, setIsLogged] = useState(false);
const [userToken, setUserToken] = useState(null);
const [userProfile, setUserProfile] = useState(null);
const [email, setEmail] = useState(null);
const [password, setPassword] = useState(null);
const [loggingIn, setloggingIn] = useState(false);
const [error, setError] = useState(null);
const AppStack = createStackNavigator();
useEffect(() => {
AsyncStorage.getItem('userProfile').then((value) => {
if (value) {
console.log(JSON.parse(value)),
setUserProfile(JSON.parse(value)),
setIsLoading(false),
setIsLogged(true);
} else {
setIsLoading(false), setIsLogged(false);
}
});
}, []);
const doLogout = async () => {
---- LOGOUT CODE
}
const doLogin = async () => {
----- LOGIN CODE and UPDATE of state and asyncstorage
}
return (
<NavigationContainer>
<AppStack.Navigator initialRouteName="Login">
<AppStack.Screen name="Login" component={Login} />
<AppStack.Screen
name="Home"
component={Home}
options={{ headerShown: false }}
/>
</AppStack.Navigator>
</NavigationContainer>
);
Login.js
const Login = ({ loggingIn, userProfile }) => {
console.log(userProfile);
return (
<View style={styles.container}>
<Button
title="Login to Site"
onPress={() => doLogin()}
disabled={loggingIn}
>
{userProfile && userProfile.name} Login to Site
</Button>
</View>
);
};
如何访问 loggingIn(甚至 userProfile)和 doLogin() 函数 我在 App.js 中设置和创建(和更新)?对于像这样的简单用途,应该有一种简单的方法(除了 useContext)。
【问题讨论】:
标签: react-native react-navigation use-context