详解反应本土页面间传递数据的几种方式

  

<强> 1。利用react-native事件DeviceEventEmitter监听广播
  

  

应用场景:

  

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

  

代码如下:
  

  

页面         componentDidMount () {//利用DeviceEventEmitter监听concactAdd事件   这一点。订阅=DeviceEventEmitter。addListener (“concactAdd”(dic)=比;{//dic为触发事件回传回来的数据//接收到更新页发送的通知,后进行的操作内容   如果(dic.approver_list) {   这一点。设置状态((preState:对象)=比;{   this.updateInputValue (preState.approver_list.concat (dic.approver_list),“approver_list”);   返回{approver_list: preState.approver_list.concat (dic.approver_list)};   });   }   如果(dic.observer_list) {   这一点。设置状态((preState:对象)=比;{   this.updateInputValue (preState.observer_list.concat (dic.observer_list),“observer_list”);   返回{observer_list: preState.observer_list.concat (dic.observer_list)};   });   }   });   …   componentWillUnmount () {   this.subscription.remove ();   }   之前      

B页面      //触发concactAdd事件广播   handleOk=(名字:[])=比;{   const{领域}=this.props;   DeviceEventEmitter。发出(concactAdd,{(领域):名称});   }   之前      

<强> 2。用react-navigation提供的路由之间
  

  

页面      //定义路由跳转函数cb表示需要传递的回调函数   出口const navigateToLinkman=(cb:函数,类型# 63;:字符串,mul& # 63;:布尔型):NavigateAction=比;   NavigationActions。导航({routeName:“主持人”,参数:{cb、类型、mul}});//跳转选择人员页面   handleSelectUser=()=比;{   Keyboard.dismiss ();   this.props.actions.navigateToLinkman(这一点。selectedUser”,真正的);   …//选择人员后的回调函数   selectedUser=(selectUser: string[])=比;{   this.setState ((preState)=比;{   const newEmails=preState.emails.concat (selectUser);   const邮件=[…新设置(newEmails)];   返回{   电子邮件,   };   });   }   之前      

B页面         handleToUser=()=比;{   …   navigation.state.params.cb(用户。电子邮件、群);   …   }   之前      

<强> 3。利用react-navigation提供的路由事件监听触发事件
  

  

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

        componentDidMount () {   this.props.navigation。addListener (“didBlur”(载荷)=比;{   如果this.modalView this.modalView.close ();   });   }   之前      

那么问题来了,为何不在页面卸载(componentWillunmount)的时候触发该事件& # 63;

  

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

  

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

详解反应本土页面间传递数据的几种方式