應用場景: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