日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

react-native页面间传递数据的几种方式

發布時間:2023/12/2 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 react-native页面间传递数据的几种方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 利用react-native 事件DeviceEventEmitter 監聽廣播

應用場景:

- 表單提交頁面, A頁面跳轉到B頁面選人, 然后返回A頁面, 需要將B頁面選擇的數據傳回A頁面。 - 多個多媒體來回切換播放,暫停后二次繼續播放等問題。

代碼如下:
A頁面

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頁面

// 觸發concactAdd事件廣播 handleOk = (names: []) => {const { field } = this.props;DeviceEventEmitter.emit('concactAdd', { [field]: names });}

2. 用react-navigation提供的路由之間

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頁面

handleToUser = () => {...navigation.state.params.cb(user.email, group);... }

3. 利用react-navigation 提供的路由事件監聽觸發事件

在A頁面路由失去焦點的時候觸發該事件

componentDidMount() { this.props.navigation.addListener('didBlur', (payload) => {if (this.modalView) this.modalView.close();});}

那么問題來了, 為何不在頁面卸載(componentWillunmount)的時候觸發該事件?

如果不了解react-native和react-navigation, 會很困惑, A頁面卸載了, 為什么還能接收到來自B頁面的數據或者事件, 原因是: react-navigation中, A頁面跳轉到B頁面, A頁面沒有卸載, 只是在它提供的路由棧中堆積,例如A跳轉到B中, A頁面不執行

componentWillunmount,當每一個路由pop掉的時候才會執行 componentWillunmount, 卸載掉當前頁面。

原文地址:https://segmentfault.com/a/1190000016928686


更多專業前端知識,請上 【猿2048】www.mk2048.com

總結

以上是生活随笔為你收集整理的react-native页面间传递数据的几种方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。