当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解react native页面间传递数据的几种方式

详解react native页面间传递数据的几种方式

2018年11月26日  | 移动技术网IT编程  | 我要评论

1. 利用react-native 事件deviceeventemitter 监听广播

应用场景:

- 表单提交页面, a页面跳转到b页面选人, 然后返回a页面, 需要将b页面选择的数据传回a页面。
- 多个多媒体来回切换播放,暂停后二次继续播放等问题。

代码如下:

a页面

 componentdidmount() {
 // 利用deviceeventemitter 监听 concactadd事件
  this.subscription = deviceeventemitter.addlistener('concactadd', (dic) => {// dic 为触发事件回传回来的数据
   // 接收到 update 页发送的通知,后进行的操作内容
   if (dic.approver_list) {
    this.setstate((prestate: object) => {
     this.updateinputvalue(prestate.approver_list.concat(dic.approver_list), 'approver_list');
     return { approver_list: prestate.approver_list.concat(dic.approver_list) };
    });
   }
   if (dic.observer_list) {
    this.setstate((prestate: object) => {
     this.updateinputvalue(prestate.observer_list.concat(dic.observer_list), 'observer_list');
     return { observer_list: prestate.observer_list.concat(dic.observer_list) };
    });
   }
  });
...
componentwillunmount() {
  this.subscription.remove();
}

b页面

// 触发concactadd事件广播
handleok = (names: []) => {
  const { field } = this.props;
  deviceeventemitter.emit('concactadd', { [field]: names });
 }

2. 用react-navigation提供的路由之间

a页面

// 定义路由跳转函数 cb表示需要传递的回调函数
export const navigatetolinkman = (cb: function, type?: string, mul?: boolean): navigateaction =>
 navigationactions.navigate({ routename: 'linkman', params: { cb, type, mul } });
 // 跳转选择人员页面
  handleselectuser = () => {
   keyboard.dismiss();
   this.props.actions.navigatetolinkman(this.selecteduser, '', true);
...
// 选择人员后的回调函数
selecteduser = (selectuser: string[]) => {
   this.setstate((prestate) => {
    const newemails = prestate.emails.concat(selectuser);
    const emails = [...new set(newemails)];
    return {
     emails,
    };
   });
  }

b页面

handletouser = () => {
  ...
  navigation.state.params.cb(user.email, group);
  ...
}

3. 利用react-navigation 提供的路由事件监听触发事件

在a页面路由失去焦点的时候触发该事件

componentdidmount() { 
this.props.navigation.addlistener('didblur', (payload) => {
     if (this.modalview) this.modalview.close();
    });
  }

那么问题来了, 为何不在页面卸载(componentwillunmount)的时候触发该事件?

如果不了解react-native和react-navigation, 会很困惑, a页面卸载了, 为什么还能接收到来自b页面的数据或者事件, 原因是: react-navigation中, a页面跳转到b页面, a页面没有卸载, 只是在它提供的路由栈中堆积,例如a跳转到b中, a页面不执行componentwillunmount,当每一个路由pop掉的时候才会执行componentwillunmount, 卸载掉当前页面。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网