詳解react native頁面間傳遞數(shù)據(jù)的幾種方式
1. 利用react-native 事件DeviceEventEmitter 監(jiān)聽廣播
應(yīng)用場景:
- 表單提交頁面, A頁面跳轉(zhuǎn)到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ā)送的通知,后進(jìn)行的操作內(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頁面
// 定義路由跳轉(zhuǎn)函數(shù) cb表示需要傳遞的回調(diào)函數(shù)
export const navigateToLinkman = (cb: Function, type?: string, mul?: boolean): NavigateAction =>
NavigationActions.navigate({ routeName: 'Linkman', params: { cb, type, mul } });
// 跳轉(zhuǎn)選擇人員頁面
handleSelectUser = () => {
Keyboard.dismiss();
this.props.actions.navigateToLinkman(this.selectedUser, '', true);
...
// 選擇人員后的回調(diào)函數(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頁面跳轉(zhuǎn)到B頁面, A頁面沒有卸載, 只是在它提供的路由棧中堆積,例如A跳轉(zhuǎn)到B中, A頁面不執(zhí)行componentWillunmount,當(dāng)每一個路由pop掉的時候才會執(zhí)行componentWillunmount, 卸載掉當(dāng)前頁面。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React 中常用的幾種路由跳轉(zhuǎn)方式小結(jié)
基本路由跳轉(zhuǎn)是最常見的一種方式,下面介紹React 中常用的幾種路由跳轉(zhuǎn)方式,感興趣的朋友一起看看吧2023-12-12
react native仿微信PopupWindow效果的實例代碼
本篇文章主要介紹了react native仿微信PopupWindow效果的實例代碼,具有一定的參考價值,有興趣的可以了解一下2017-08-08
webpack構(gòu)建react多頁面應(yīng)用詳解
這篇文章主要介紹了webpack構(gòu)建react多頁面應(yīng)用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
React中的useState和setState的執(zhí)行機制詳解
這篇文章主要介紹了React中的useState和setState的執(zhí)行機制,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03

