react-native页面间传递数据的几种方式
生活随笔
收集整理的這篇文章主要介紹了
react-native页面间传递数据的几种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 利用react-native 事件DeviceEventEmitter 監聽廣播
應用場景:
- 表單提交頁面, A頁面跳轉到B頁面選人, 然后返回A頁面, 需要將B頁面選擇的數據傳回A頁面。 - 多個多媒體來回切換播放,暫停后二次繼續播放等問題。代碼如下:
A頁面
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页面间传递数据的几种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 正确判断js数据类型 总结记录
- 下一篇: 一个页面从输入URL到加载显示完成,发生