将数据从Android Native传递到React Native

时间:2019-02-12 06:57:11

标签: android reactjs react-native hybrid-mobile-app

我正在构建一个具有Android本机和React Native相互通信的集成应用程序。

为了将数据从本机发送到React本机,我尝试使用初始道具传递数据,但是它不起作用并且显示未定义。然后我尝试使用DeviceEventEmitter可以工作,但是有一个小问题。

已编辑:

这是代码段

class Details extends Component {

    constructor(props){
    super(props);
            this.state={data: '', id: '278'}
    }

    componentDidMount(){
        const eventEmitter = new NativeEventEmitter();
        this.subscription = eventEmitter.addListener('customEventName',(e: Event)=>{
            this.setState({id: e.key1});
            console.warn(this.state.id);    
        });

        const API_key = "APIkey"
        console.warn(this.state.id);

        const URL = "https://api.themoviedb.org/3/movie/" + this.state.id + "?api_key=" + API_key + "&language=en-USs"

        return fetch(URL, {
          method: 'GET'
        })
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({
            data: responseJson,
          },
          function(){
          });
        })
        .catch((error) =>{
          console.error(error);
        });
     }

    componentWillUnmount(){
        this.subscription.remove();
    }

    render() {
        return(
            /*something*/
        );
    }
}

id的值已成功从本机组件发送到React本机组件。

问题console.warn()中的addlistener()console.warn()之后显示,下面是API_key,因此是{{1 }}尚未更新。

请提供任何帮助。

2 个答案:

答案 0 :(得分:0)

您的事件寄存器应该如下所述,因为您正在注册事件,因此this的范围应该是事件处理程序特定的,因此,如果要访问父范围,则需要使用箭头函数,例如下面提到。

 DeviceEventEmitter.addListener('customEventName',(e: Event)=> {
        this.id = e.key1
        console.warn("inside event emitter", this.id);
    });

答案 1 :(得分:0)

如果您成功举办了活动,那么我认为这只是一个React问题。

您似乎想在成功获取ID之后获取 ,但是您正试图立即在componentDidMount中获取。

由于获取是一种副作用,您可能希望像这样使用componentDidUpdate

import { NativeEventEmitter } from 'react-native'

    constructor(props){
      super(props);
      this.state={
        data: '', 
        id: ''
      }
    }

    componentDidMount(){
        const eventEmitter = new NativeEventEmitter();
        this.subscription = eventEmitter.addListener('customEventName',(e: Event)=>{
            this.setState({id: e.key1});
            console.warn(this.state.id);    
        });
     }

    componentDidUpdate() {
      const { id } = this.state

      if (id) {
       const URL = "https://api.themoviedb.org/3/movie/" + this.state.id + "?api_key=" + API_key + "&language=en-USs"

        return fetch(URL, {
          method: 'GET'
        })
       // ... etc
      }
    }

    // ...etc

请注意,id开头为空。