Headless Task use inside component with React Native

偶尔善良 提交于 2019-12-12 04:31:36

问题


I am trying to run a background task using headlessjs in react-native. The problem is that I am unable to access the async task inside the component in order to show it on the view. Here's my default component.

import React, { Component } from 'react';

import {
  AppRegistry,
  Text,
  View,
  NativeModules
} from 'react-native';


module.exports = NativeModules.ToastAndroid;

someTask = require('./SomeTaskName.js');



export default class test2 extends Component {

   constructor() {
      super()
      this.state = {
         myText: 'My Original Text'
      }
   }
   updateText = () => {
      this.setState({myText: 'My Changed Text'});s
   }

  componentDidMount(){
    this.setState({myText: someTask});
    someTask.then(function(e){           //<--- error
      console.log("lala" + e);
    });
  }
  render() {
    return (
         <View>
            <Text>
              abc
            </Text>
         </View>
    );
  }
}



AppRegistry.registerComponent('test2', () => test2);
AppRegistry.registerHeadlessTask('SomeTaskName', () => someTask);

As mentioned in the code, I get the error undefined is not a function. I don't know how to make this work. My SomeTaskName.js looks like this.

SomeTaskName.js

module.exports = async (taskData) => {
  return taskData.myname;
}

The idea is to simply get the data from the service and show it on the UI.


回答1:


The solution was to simply move the code inside the componentDidMount function. Here's how I achieved it.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';

import {
  AppRegistry,
  Text,
  View,
  Image
} from 'react-native';


export default class test2 extends Component {

   constructor() {
      super()
      this.state = {
         myText: '1'
      }
   }


  componentWillUnmount() {
  }
  componentDidMount(){
    someTask = async (taskData) => {
        this.setState({ myText: taskData.myname});
    }
  };

  }
  render() {

    return (<Text>Working</Text>);
  }
}



AppRegistry.registerHeadlessTask('SomeTaskName', () => someTask);
AppRegistry.registerComponent('test2', () => test2);



回答2:


You can replace :

someTask = require('./SomeTaskName.js');

by

import SomeTaskName from './SomeTaskName'


来源:https://stackoverflow.com/questions/43322455/headless-task-use-inside-component-with-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!