首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用React Hooks React Native混淆替换

使用React Hooks React Native混淆替换
EN

Stack Overflow用户
提问于 2020-07-30 11:25:41
回答 1查看 34关注 0票数 0

我试着用React Hooks让异步等待if条件。下面的代码是在我试图让它成为React Hooks之前的代码:

代码语言:javascript
复制
async startService() {
        if (Platform.OS !== 'android') {
            console.log('Only Android platform is supported');
            return;
        }
        if (Platform.Version >= 26) {
            const channelConfig = {
                id: 'ForegroundServiceChannel',
                name: 'Notification Channel',
                description: 'Notification Channel for Foreground Service',
                enableVibration: true,
                importance: 2
            };
            await VIForegroundService.createNotificationChannel(channelConfig);
        }
    }

我试着把它放进React Hooks

代码语言:javascript
复制
 useEffect(() => {
    async function startService() {
      if (Platform.OS !== 'android') {
          console.log('Only Android platform is supported');
          return;
      }
      if (Platform.Version >= 26) {
          const channelConfig = {
              id: 'ForegroundServiceChannel',
              name: 'Notification Channel',
              description: 'Notification Channel for Foreground Service',
              enableVibration: false,
              importance: 2
          };
          await VIForegroundService.createNotificationChannel(channelConfig);
      }
      const notificationConfig = {
          id: 3456,
          title: 'Foreground Service',
          text: 'Foreground service is running',
          icon: 'ic_notification',
          priority: 0
      };
      if (Platform.Version >= 26) {
          notificationConfig.channelId = 'ForegroundServiceChannel';
      }
      await VIForegroundService.startService(notificationConfig);
  }startService();
  }, []);

我还试图在我的jsx中调用它,如下所示:

代码语言:javascript
复制
<Button onPress={() => this.startService()}>
      <Text>Tes</Text>
 </Button>

它没有工作,我写错了吗?

EN

回答 1

Stack Overflow用户

发布于 2020-07-30 13:06:16

根据您的代码,函数startService()的作用域在useEffect内的箭头函数内。它只能从useEffect中的箭头函数中访问。你要做的就是在一个没有作用域的块中调用一个函数。

第二件事,useEffect不是显式调用的东西。效果将基于依赖数组启动。Ryan Florance很好地解释了如何在这个video中使用useEffect钩子。

要使您的代码工作,您根本不需要useEffect。只需将startService()的函数定义移出useEffect,移到main函数内部或函数外部的某个地方(如果它没有任何其他依赖项)。

如果您的目标是只启动一次startService(),则可以按如下方式使用useEffect:

代码语言:javascript
复制
useEffect(() => {
    startService();
},[]);

另外,Button组件的用法是不正确的。如下所示:

代码语言:javascript
复制
<Button title="Tes" onPress={startService} />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63165735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档