无头任务在组件内部使用React Native

时间:2017-04-10 11:53:46

标签: react-native react-native-android

我正在尝试使用headlessjs in react-native运行后台任务。问题是我无法访问组件内的异步任务,以便在视图上显示它。这是我的默认组件。

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);

如代码中所述,我收到错误undefined is not a function。我不知道如何做这项工作。我的SomeTaskName.js看起来像这样。

SomeTaskName.js

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

我们的想法是简单地从服务中获取数据并在UI上显示它。

2 个答案:

答案 0 :(得分:1)

解决方案是简单地将代码移到componentDidMount函数中。这就是我实现它的方式。

/**
 * 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);

答案 1 :(得分:0)

您可以替换:

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

通过

import SomeTaskName from './SomeTaskName'