在 React Native 的组件内部使用 Headless Task [英] Headless Task use inside component with React Native

查看:73
本文介绍了在 React Native 的组件内部使用 Headless Task的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

推荐答案

解决方案是简单地将代码移动到 componentDidMount 函数内.这是我如何实现的.

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

这篇关于在 React Native 的组件内部使用 Headless Task的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆