詳解react native頁面間傳遞數(shù)據(jù)的幾種方式
1. 利用react-native 事件DeviceEventEmitter 監(jiān)聽廣播
應用場景:
- 表單提交頁面, A頁面跳轉到B頁面選人, 然后返回A頁面, 需要將B頁面選擇的數(shù)據(jù)傳回A頁面。
- 多個多媒體來回切換播放,暫停后二次繼續(xù)播放等問題。
代碼如下:
A頁面
componentDidMount() { // 利用DeviceEventEmitter 監(jiān)聽 concactAdd事件 this.subscription = DeviceEventEmitter.addListener('concactAdd', (dic) => {// dic 為觸發(fā)事件回傳回來的數(shù)據(jù) // 接收到 update 頁發(fā)送的通知,后進行的操作內(nèi)容 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頁面
// 觸發(fā)concactAdd事件廣播 handleOk = (names: []) => { const { field } = this.props; DeviceEventEmitter.emit('concactAdd', { [field]: names }); }
2. 用react-navigation提供的路由之間
A頁面
// 定義路由跳轉函數(shù) cb表示需要傳遞的回調函數(shù) 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); ... // 選擇人員后的回調函數(shù) 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 提供的路由事件監(jiān)聽觸發(fā)事件
在A頁面路由失去焦點的時候觸發(fā)該事件
componentDidMount() { this.props.navigation.addListener('didBlur', (payload) => { if (this.modalView) this.modalView.close(); }); }
那么問題來了, 為何不在頁面卸載(componentWillunmount)的時候觸發(fā)該事件?
如果不了解react-native和react-navigation, 會很困惑, A頁面卸載了, 為什么還能接收到來自B頁面的數(shù)據(jù)或者事件, 原因是: react-navigation中, A頁面跳轉到B頁面, A頁面沒有卸載, 只是在它提供的路由棧中堆積,例如A跳轉到B中, A頁面不執(zhí)行componentWillunmount,當每一個路由pop掉的時候才會執(zhí)行componentWillunmount, 卸載掉當前頁面。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
react native仿微信PopupWindow效果的實例代碼
本篇文章主要介紹了react native仿微信PopupWindow效果的實例代碼,具有一定的參考價值,有興趣的可以了解一下2017-08-08React中的useState和setState的執(zhí)行機制詳解
這篇文章主要介紹了React中的useState和setState的執(zhí)行機制,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03