版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
ReactReactNativeReactNative課堂目App導(dǎo)航框架設(shè)設(shè)計歡迎頁進入主頁導(dǎo)App導(dǎo)歡迎頁面5秒后進入主設(shè)計一個轉(zhuǎn)場工具類歡迎頁改主頁設(shè)計底部導(dǎo)ReduxReactNavigation結(jié)合集成第一步:安裝s第二步:配置n第四步:在組件中應(yīng)案例:使用react-navigaton+redux修改狀態(tài)欄顏色創(chuàng)建Actions/theme創(chuàng)建Reducer/themeRN網(wǎng)絡(luò)編數(shù)據(jù)刪除數(shù)離線緩存框架設(shè)校驗時完整代碼實課前回ReactNavigationReactNavigation概念與屬性介紹課堂目掌握reactnavigation了解redux在RN項目(使用reactnavigation)中的集成方式App仿主流APP設(shè)計一個導(dǎo)航歡迎頁面設(shè)importimportReact,{Component}fromimport{ tform,StyleSheet,Text,View}from"react-native";exportdefaultclass ePageextendsComponent{{return<View<Texte}conststyles=StyleSheet.create({{flex:1,justifyContent:"center",alignItems:"center",backgroundColor:"#F5FCFF"{textAlign:"center",margin:10App主頁設(shè)importimportReact,{Component}fromimport tform,StyleSheet,Text,View}from"react-exportdefaultclassHomePageextendsComponent{{super(props);console.disableYellowBox=true;}render(){return<View<Texteto}}conststyles=StyleSheet.create({{flex:1,justifyContent:"center",alignItems:"center",backgroundColor:"#F5FCFF"{textAlign:"center",margin:10}詳情頁importimportReact,{Component}fromimport tform,StyleSheet,Text,View}from"react-exportdefaultclassDetailPageextendsComponentrender()returnreturn<View<Texteto}}conststyles=StyleSheet.create({{flex:1,justifyContent:"center",alignItems:"center",backgroundColor:"#F5FCFF"{textAlign:"center",margin:10}安裝reactnavigation與第圖標庫react-native-vector-yarnyarnaddreact-navigation#orwithnpm#npminstall--savereact-yarnaddreact-native-gesture-handler#orwithnpm#npminstall--savereact-native-gesture-react-nativelinkreact-native-gesture-yarnaddreact-native-vector-react-nativelinkreact-native-vector-###記得關(guān)閉模擬?,服務(wù)?,重新啟動項設(shè)計歡迎頁進入主頁導(dǎo)#####}from"react-importHomePagefrom"../Pages/HomePage"; ePagefrom" importDetailPagefrom"../Pages/DetailPage";//定義歡迎constAppInitNavigator= ePage:{ navigationOptions:header:}}//定義主頁constAppMainNavigator=createStackNavigator({HomePage:{screen:HomePage,navigationOptions:{header:}DetailPage:{screen:}exportInit:AppInitNavigator,Main:App導(dǎo)importimportAppfrom歡迎頁面5秒后進入主componentDidMountcomponentDidMount()this.timer=setTimeout((){const{navigation}=},}componentWillUnmount()this.timer&&設(shè)計一個轉(zhuǎn)場工具類exportdefaultclassexportdefaultclassNavigationUtil//跳轉(zhuǎn)到指定頁staticgoPage(props,page)constnavigation=NavigationUtil.navigation;navigation.navigate(page,{}//gostatic{const{navigation}=}//回到主 {const{navigation}=}}歡迎頁importimportNavigationUtilfromcomponentDidMount()this.timer=setTimeout((){navigationUtil.resetToHomePage({},}主頁設(shè)計底部導(dǎo)importimportReact,{Component}fromimport{ tform,StyleSheet,Text,View}from"react-native";import{}from"react-importIndexPagefrom"./IndexPage";importMyPagefrom"./MyPage";importFontAwesomefrom"react-native-vector-icons/FontAwesome";constTABS={IndexPage:{screen:IndexPage,navigationOptions:tabBarLabel:"首頁tabBarIcon:({tintColor,focused})=><FontAwesomename={"home"}size={26}style={{color:tintColor}})}MyPage:{screen:MyPage,navigationOptions:tabBarLabel:"我的tabBarIcon:({tintColor,focused})=><FontAwesomename={"user"}size={26}style={{color:tintColor}})}}exportdefaultclassHomePageextends{constructor(props){console.disableYellowBox=true;}}_TabNavigator()return}render()constTabs=this._TabNavigator();return<Tabs/>;}}conststyles=StyleSheet.create({{flex:1,justifyContent:"center",alignItems:"center",backgroundColor:"#F5FCFF"{textAlign:"center",margin:10}Index頁面頂部導(dǎo)航設(shè)importimportReact,{Component}fromimport{ tform,StyleSheet,Text,View}from"react-import{}from"react-importNavigationUtilfromexportdefaultclassIndexPageextends{constructor(props){this.tabNames=["React}_genTabs(){consttabs={};this.tabNames.forEach((item,index)=>{tabs[`tab${index}`]={screen:props=><IndexTab{...props}tabName={item}/>,navigationOptions:{title:}return}render()constTabNavigatorcreateAppContainer(createMaterialTopTabNavigator(this._genTabs(),{{upperCaseLabel:false,scrollEnabled:true,}return<Viewstyle={{flex:1,marginTop:30<TabNavigator}}classIndexTabextends{render()const{tabName}=ps;return(<View<Text etotitle={"gotoDetailPage"}onPress={()=>{}}constconststylesStyleSheet.create({container:{flex:1,justifyContent:"center",alignItems:"center",backgroundColor:"#F5FCFF"{fontSize:20,textAlign:"center",margin:10}Redux與ReactNavigation結(jié)合集ReduxReactNavigation有點復(fù)雜Redux是自頂向下管理一套狀態(tài),ReactNavigation也是自頂向下管理一套狀態(tài)甚至頁面,這倆融合起來就有點了yarnaddyarnaddyarnaddreact-redux//因為redux其實是可以獨立運行的js項目,但使用在react項目中,還需要yarnaddreact-navigation-redux-helpers//在使用ReactNavigation的項目中,想要集成redux就必須要引入react-navigation-redux-helpers這個庫importimport{connect}from"react-import{}from"react-navigation-redux-AppWithNavigationState,這個高階組件完成了navigationprop的替換,改成了使用redux修改AppNavitor為RootNavigator并不再默認導(dǎo)exportconstRootNavigator=Init:AppInitNavigator,Main:AppMainNavigatorconstAppWithNavigationState=createReduxContainer(RootNavigator,是ReactNavigation還不能識別,所以還需要最后一步——創(chuàng)建一個中間件,把需要導(dǎo)航的組件exportconstexportconstmiddleware=createReactNavigationReduxMiddleware(state=>state.nav,然后使用Redux的connect函數(shù)再封裝一個高階組件,默認//State//State到Props的映射constmapStateToProps=state{returnstate://使用Redux的connect函數(shù)再封裝一個高階組件,連接React組件與Reduxstoreexportdefaultconnect(mapStateToProps)(AppWithNavigationState);完整代}from"react-importHomePagefrom"../Pages/HomePage"; ePagefrom" importDetailPagefrom"../Pages/DetailPage";//引入import{connect}from"react-//reduxifyNavigator,react-navigation-redux-helpers3.0變更}from"react-navigation-redux-exportconst ="Init";//設(shè)置根路由constAppInitNavigatorcreateStackNavigator({ePage:{ navigationOptions:{header:null}}constAppMainNavigator=createStackNavigator({HomePage:{screen:HomePage,navigationOptions:{header:}DetailPage:{screen:}exportconstRootNavigator=Init:AppInitNavigator,Main:AppMainNavigator1.初始化react-navigation與redux的中間件該方法的一個很大的作用就是為reduxifyNavigator的key設(shè)置actionSubscribers(行為訂閱者//react-navigation-redux-hepers3.0變更,createRectNavigatonReduxMidleware數(shù)順序發(fā)生了變化exportconstmiddleware=createReactNavigationReduxMiddleware(state=>state.nav,/*2.將根導(dǎo)航?組件傳遞給reduxifyNavigator函數(shù)并返回一個將navigationstate和dispatch函數(shù)作為props的新組件使用createReduxContainer方法,將RootNavigator封裝成高階組這個高階組件完成了navigationprop的替換,改成了使用redux里的*constAppWithNavigationState=createReduxContainer(RootNavigator,//State到Props的映射constmapStateToProps=state{returnstate://使用Redux的connect函數(shù)再封裝一個高階組件,連接React組件與Reduxstoreexportdefaultconnect(mapStateToProps)(AppWithNavigationState);importimport{combineReducers}from"redux";importthemefrom"./theme";import ,RootNavigator}fromconstnavState /**上面的代碼創(chuàng)建了一個導(dǎo)航action(表 打),那么我們就可以通過actionstate,通過方*法getStateForAction(action,*倆參數(shù),一個是新的action,一個是當前的導(dǎo)航state,返回新的狀態(tài),當沒有辦法執(zhí)行這個action的時候,就返回*null。constnavReducer=(state=navState,action)=>constnextState=RootNavigator.router.getStateForAction(action,如果`nextState`為null或未定義,只需返回原始`state`returnnextState||state;3.合并@type{Reducer<any>|Reducer<any,constindex=combineReducers({nav:theme:exportdefaultimportimport{applyMiddleware,createStore}from"redux";importreducersfrom"../Reducer";import{middleware}fromconstmiddlewares=*創(chuàng)建exportdefaultcreateStore(reducers,importimportReact,{Component}from'react';import{Provider}from'react-redux';importAppNavigatorfromimportstorefromtypeProps=exportdefaultclassAppextends{render()*將store傳遞給App框return<Provider}}搞定 創(chuàng)建###Types.js###Types.jsexportdefault{THEM_CHANGE:"THEM_CHANGE",THEM_INIT:"THEM_INIT"創(chuàng)建importimportTypesfromexportfunctiononThemeChange(theme){return{type:Types.THEM_CHANGE,theme:theme}創(chuàng)建importimportTypesfromconstdefaultState{theme:exportdefaultfunctiononAction(state=defaultState,{switch(action.type)return{theme:return}}在Reducer中聚constconstindex=combineReducers({nav:theme:訂閱importimportReact,{Component}fromimport{Button, tform,StyleSheet,Text,View}from"react-native";import{}from"react-importIndexTabfrom"../Pages/IndexTab";import{connect}from"react-redux";import{onThemeChange}fromimportnavigationUtilfrom"../Navigator/navigationUtil";classIndexPageextendsComponent{{super(props);this.tabNames=["ReactNative"}_genTabs(){consttabs={};this.tabNames.forEach((item,index)=>{tabs[`tab${index}`]={screen:props=><IndexTab{...props}tabName={item}/>,navigationOptions:{title:}return}render()constTabBackground=ps.theme;constTabNavigatorcreateAppContainer(createMaterialTopTabNavigator(this._genTabs(),{{tabStyle:{},upperCaseLabel:false,scrollEnabled:true,style:{//選項卡背backgroundColor:indicatorStyle:height:2,backgroundColor:labelStyle:fontSize:marginTop:marginBottom:}}return<Viewstyle={{flex:1,marginTop:30<TabNavigator}}conststylesStyleSheet.create({container:flexflex:justifyContent:"center",alignItems:"center",backgroundColor:"#F5FCFF"{fontSize:20,textAlign:"center",margin:10}constmapStateToProps=state=>({theme:state.theme.themeexportdefault在上述代碼中我們訂閱了store中的ps.theme獲取到所訂閱的themestate了。importimportReact,{Component}fromimport{ tform,StyleSheet,Text,View}from"react-import{connect}from"react-import{onThemeChange}fromclassIndexTabextends{render()const{tabName}=ps;return(<View<Textetotitle={"gotoDetailPage"}onPress={()=>{navigationUtil.goPage(ps,onPress={()=>{//navigationUtil.goPage(ps,}}conststyles=StyleSheet.create({{flex:1,justifyContent:"center",alignItems:"center",backgroundColor:"#F5FCFF"{textAlign:"center",margin:10}constmapDispatchToProps=dispatch=>({onThemeChange:theme=>dispatch(onThemeChange(theme))exportRN發(fā)起請要從任意地址獲取內(nèi)容的話,只需簡單地將作為參數(shù)傳遞給fetch方法即可(fetch這個詞本身也就是獲取的意思)Fetch還有可選的第二個參數(shù),可以用來定制HTTP請求一些參數(shù)。你可以指定header參數(shù),或是指定使用POST方法,又或是提交數(shù)據(jù)等等:{method:'POST',headers:{Accept:'application/json','Content-Type':'application/json',JSON.stringify({firstParam:'yourValue',secondParam:ars中的Content-TypeCtt-Typey的格式也有區(qū)別。到底應(yīng)該采用什么樣的Content-Type取決于服務(wù)?端,所以請和服務(wù)?下{method:'POST',headers:{'Content-Type':'application/x-www-form-body:Fetch方返回一個Promise,這種模式可以簡化異步風(fēng)格的代functionfunctiongetMoviesFromApiAsync(){returnfetch('.then((response)=>.then((responseJson){return.catch((error){ReactNativeES2017標準中的asyncawait語法注意這個方法前面有async關(guān)鍵asyncasyncfunction{try注意這里的await語句,其所在的函數(shù)必須有asyncletresponse=awaitfetch('letresponseJson=awaitresponse.json();returnresponseJson.movies;}catch{}}別忘了catch住fetch可能拋出的異常,否則出錯時你可能看不到任何注意:使用Chrome調(diào)試目前無法觀測到ReactNative中的網(wǎng)絡(luò)請求,你可以使用第的react-重要,處理一的HTP狀態(tài)碼時,從ftch()的pomise不會被標記為eject該HTTP404或50。相反,它會將omiseveslveok屬為fals被為eject。一次請求沒有調(diào)用ejecteslve情況下,再判斷sos.ktruletleturl=`http.then(response{if{return}thrownewError("Networkresponsewasnot.then(responseText{.catch(e{數(shù)據(jù)AsyncStorage是一個簡單的、異步的、持久化的Key-Value系統(tǒng),它對于App來說是全局性的??捎脕泶鍸ocalStorage。我們推薦您在AsyncStorage的基礎(chǔ)上做一層抽象封裝,而不是直接使用AsyncStorage在iOS上,AsyncStorage在原生端的實現(xiàn)是把較小值存放在序列化的字典中,而把較大值寫入單獨的文件。在Android上,AsyncStorage會嘗試使用RocksDB,或退而選擇。在新版本的RN中AS已經(jīng)從RN框架中移除了,使用第庫 async-storage來替代。安##$yarnmunity/async-#$react-nativemunity/async-使importimportAsyncStoragefrommunity/async-數(shù)asyncasyncerr&&err&&awaiterr&&}}數(shù)asyncasyncerr&&err&&constvalue=awaitAsyncStorage.getItem(Key)err&&}}刪除數(shù)asyncasyncerr&&err&&awaiterr&&}}離線緩存有什么體的我制們線驗。務(wù)戶離線緩存有什么數(shù)據(jù)的實時性要求不高離線緩存的策優(yōu)先從服務(wù)?獲取數(shù)據(jù),數(shù)據(jù)返回后同步到本地數(shù)據(jù)庫,如果發(fā)生網(wǎng)絡(luò)故障,才從本地獲取數(shù)離線緩存框架的優(yōu)先從本地實現(xiàn)思returnnewif(wrapdata&&DataStore.checkTimestampValid(wrapdata.timestamp)){}.catch(error{.then(data{.catch(error{}首先需要實現(xiàn)對數(shù)據(jù)的importimportAsyncStoragefrommunity/async-exportdefaultclassDataStore{saveData(url,data,callback){if(!data||!url)AsyncStorage.setItem(url,JSON.stringify(this._wrapData(data)),}}//上述代碼url作為緩存數(shù)據(jù)的key,接受一個Object的參數(shù)data為value,因為AS是無法保存的,所以需要把它序列化成給離線的數(shù)據(jù)添加一個時間戳,便于計_wrapData_wrapData(data)return{data:data,timestamp:newDate().getTime()};////本地時間,推薦服務(wù)?間}獲取本地數(shù)returnnewresolve(JSON.parse(result))//getItem獲取到的是string為}}獲取網(wǎng)絡(luò)數(shù)returnnewPromise((resolve,reject)=>{fetch(urreturn}thrownewError('networkresponsewasnot校驗時staticstatic{constcurrentDate=newDate();consttargetDate=newDate();if(currentDate.getMonth()!==targetDate.getMonth())returnfalse;if(currentDate.getDate()!==targetDate.getDate())returnfalse;if(currentDate.getHours()-targetDate.getHours()>4)returnfalse;//有效期//if(currentDate.getMinutes()-targetDate.getMinutes()>1)returnfalse;returntrue;}完整代碼實importimportAsyncStoragefrommunity/async-exportdefaultclassDataStorestatic{constcurrentDate=newDate();consttargetDate=newDate();if(currentDate.getMonth()!==targetDate.getMonth())returnfalse;if
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 天府新區(qū)信息職業(yè)學(xué)院《世界經(jīng)典建筑解析》2023-2024學(xué)年第一學(xué)期期末試卷
- 公司裝修發(fā)票合同范例
- 系統(tǒng)訓(xùn)練幼兒體能課程設(shè)計
- 到貨合同范例
- 單位電路施工合同范例
- 農(nóng)機合伙合同范例
- 縣衙漢服租借合同范例
- 第六章 愛護植被,綠化祖國教學(xué)實錄 2023-2024學(xué)年人教版生物七年級上冊
- 中介廠區(qū)駐廠合同范例
- 單位寫合同范例
- 環(huán)保設(shè)施安全風(fēng)險評估報告
- 數(shù)字邏輯與計算機組成 習(xí)題答案 袁春風(fēng) 第3章作業(yè)批改總結(jié)
- 要求降低物業(yè)費的申請書范本
- 焊接機器人行業(yè)分析研究報告
- PI形式發(fā)票范文模板
- 北京房產(chǎn)證(共同共有)模板
- 氫氧化鈉安全技術(shù)說明書
- 部編二年級語文上冊第七單元表格式教案
- 2023光伏電站無人機智能巡檢技術(shù)標準
- 鋼筋籠吊裝方案履帶吊
- 中職英語基礎(chǔ)模塊第二版8單元說課課件
評論
0/150
提交評論