小编kev*_*954的帖子

无法在异步函数中设置上下文?

好吧,请对我温柔一点,我对 React Native 还很陌生,但我正在使用 Context 来管理我的 React Native 项目中的一些状态。这是我陷入困境的一个例子

在功能组件的顶部我有这个......

import DataContext from "../../contexts/DataContext";
import AsyncStorage from "@react-native-community/async-storage";

const AccountHomepageScreen = ({navigation}) => {

     const { data, updateInfo} = useContext(DataContext);


     const getUserFromAsync = async () => {
         try {
             const value = await AsyncStorage.getItem('user_id');
             if(value !== null) {

                 //shows user_id in Alert no problem
                 alert(value);

                 //but this does not work?!?!
                 updateInfo('userId', value);
            
             }
         } catch(e) {
             // error reading value
            return false;
         }
     }
}

useEffect(() => {
    getUserFromAsync();
}, …
Run Code Online (Sandbox Code Playgroud)

reactjs react-native react-context

1
推荐指数
1
解决办法
2313
查看次数

标签 统计

react-context ×1

react-native ×1

reactjs ×1