【问题标题】:Cannot access state outside NativeModules after creating Native Bridge React Native创建 Native Bridge React Native 后无法访问 NativeModules 之外的状态
【发布时间】:2021-06-09 14:55:04
【问题描述】:

在使用原生 android 创建桥后,我试图访问从 NativeModule 收到的结果之外的状态。数据显示在console.log中,但外部无法访问。

NativeModules["GetapplistModule"].getNonSystemApps(res => {
    var pairs = [];
    for(var key in res){
      var obj = JSON.parse(res[key]);
      pairs.push(obj);
    }
    const [AppData] = React.useState(pairs);
  });

 type AppProps = React.ComponentProps<typeof AppProps>;
 export const notificationTweets: Array<AppProps> = {AppData};

【问题讨论】:

    标签: react-native bridge


    【解决方案1】:

    我用useEffect解决了这个问题

    如果您遇到同样的问题,请将您的函数包装在 useEffect 中并在范围内分配状态,如下所示。

    const [AppData, setApps] = React.useState([]);
    React.useEffect(() => {
    NativeModules["GetapplistModule"].getNonSystemApps(res => {
        var pairs = [];
        for(var key in res){
          var obj = JSON.parse(res[key]);
          pairs.push(obj);
        }
        setApps(pairs);
      });
    
     type AppProps = React.ComponentProps<typeof AppProps>;
     export const notificationTweets: Array<AppProps> = {AppData};
    }, []);
    

    现在,您可以在任何地方访问状态

    console.log(AppData);
    

    希望对遇到同样问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多