应用场景:react
- 表单提交页面, A页面跳转到B页面选人, 而后返回A页面, 须要将B页面选择的数据传回A页面。 - 多个多媒体来回切换播放,暂停后二次继续播放等问题。
代码以下:
A页面react-native
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页面app
// 触发concactAdd事件广播 handleOk = (names: []) => { const { field } = this.props; DeviceEventEmitter.emit('concactAdd', { [field]: names }); }
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页面this
handleToUser = () => { ... navigation.state.params.cb(user.email, group); ... }
在A页面路由失去焦点的时候触发该事件spa
componentDidMount() { this.props.navigation.addListener('didBlur', (payload) => { if (this.modalView) this.modalView.close(); }); }
那么问题来了, 为什么不在页面卸载(componentWillunmount)的时候触发该事件?code
若是不了解react-native和react-navigation, 会很困惑, A页面卸载了, 为何还能接收到来自B页面的数据或者事件, 缘由是: react-navigation中, A页面跳转到B页面, A页面没有卸载, 只是在它提供的路由栈中堆积,例如A跳转到B中, A页面不执行componentWillunmount
,当每个路由pop掉的时候才会执行componentWillunmount
, 卸载掉当前页面。component