【问题标题】:How do I call a function when app running in background using react-native-background-task?当应用程序使用 react-native-background-task 在后台运行时如何调用函数?
【发布时间】:2020-01-17 10:55:06
【问题描述】:

当应用程序在后台运行时,我想使用“react-native-background-task”组件调用componentDidMount() 或任何其他函数。这是我想使用但不知道是否正确的代码:

import BackgroundTask from 'react-native-background-task'

BackgroundTask.define(async () => {
  this.componentDidMount();
  BackgroundTask.finish();
});

export default class MyClass extends Component {
  componentDidMount() {
    this.someTask();
  }
}

【问题讨论】:

    标签: reactjs react-native background-task


    【解决方案1】:

    你能更具体地解释一下吗?如果你想在应用启动时做任何思考,你可以在 App.js 的 componentDidMount();

    componentDidMount() {
        this.job();
    }
    
    async job(){
         BackgroundTask.define(() => {
           console.log('Hello from a background task')
           BackgroundTask.finish()
         })
    }
    

    或者:

    BackgroundTask.define(() => {
      console.log('Hello from a background task')
      BackgroundTask.finish()
    })
    
    class MyApp extends React.Component {
      componentDidMount() {
        BackgroundTask.schedule()
      }
    
      render() {
        return <Text>Hello world</Text>
      }
    }
    

    【讨论】:

    • 我刚刚发现,当应用的状态发生变化时,我可以使用 AppState 来调用一个函数。那不是更好的解决方案吗?
    • 其实我不确定哪个更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多