开课吧web全栈架构师12期课件38rn第三节react native课程大纲_第1页
开课吧web全栈架构师12期课件38rn第三节react native课程大纲_第2页
开课吧web全栈架构师12期课件38rn第三节react native课程大纲_第3页
开课吧web全栈架构师12期课件38rn第三节react native课程大纲_第4页
开课吧web全栈架构师12期课件38rn第三节react native课程大纲_第5页
已阅读5页,还剩25页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

ReactReactNativeReactNative课堂目App导航框架设设计欢迎页进入主页导App导欢迎页面5秒后进入主设计一个转场工具类欢迎页改主页设计底部导ReduxReactNavigation结合集成第一步:安装s第二步:配置n第四步:在组件中应案例:使用react-navigaton+redux修改状态栏颜色创建Actions/theme创建Reducer/themeRN网络编数据删除数离线缓存框架设校验时完整代码实课前回ReactNavigationReactNavigation概念与属性介绍课堂目掌握reactnavigation了解redux在RN项目(使用reactnavigation)中的集成方式App仿主流APP设计一个导航欢迎页面设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主页设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-###记得关闭模拟器,服务器,重新启动项设计欢迎页进入主页导#####}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导importimportAppfrom欢迎页面5秒后进入主componentDidMountcomponentDidMount()this.timer=setTimeout((){const{navigation}=},}componentWillUnmount()this.timer&&设计一个转场工具类exportdefaultclassexportdefaultclassNavigationUtil//跳转到指定页staticgoPage(props,page)constnavigation=NavigationUtil.navigation;navigation.navigate(page,{}//gostatic{const{navigation}=}//回到主 {const{navigation}=}}欢迎页importimportNavigationUtilfromcomponentDidMount()this.timer=setTimeout((){navigationUtil.resetToHomePage({},}主页设计底部导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页面顶部导航设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结合集ReduxReactNavigation有点复杂Redux是自顶向下管理一套状态,ReactNavigation也是自顶向下管理一套状态甚至页面,这俩融合起来就有点了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并不再默认导exportconstRootNavigator=Init:AppInitNavigator,Main:AppMainNavigatorconstAppWithNavigationState=createReduxContainer(RootNavigator,是ReactNavigation还不能识别,所以还需要最后一步——创建一个中间件,把需要导航的组件exportconstexportconstmiddleware=createReactNavigationReduxMiddleware(state=>state.nav,然后使用Redux的connect函数再封装一个高阶组件,默认//State//State到Props的映射constmapStateToProps=state{returnstate://使用Redux的connect函数再封装一个高阶组件,连接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";//设置根路由constAppInitNavigatorcreateStackNavigator({ePage:{ navigationOptions:{header:null}}constAppMainNavigator=createStackNavigator({HomePage:{screen:HomePage,navigationOptions:{header:}DetailPage:{screen:}exportconstRootNavigator=Init:AppInitNavigator,Main:AppMainNavigator1.初始化react-navigation与redux的中间件该方法的一个很大的作用就是为reduxifyNavigator的key设置actionSubscribers(行为订阅者//react-navigation-redux-hepers3.0变更,createRectNavigatonReduxMidleware数顺序发生了变化exportconstmiddleware=createReactNavigationReduxMiddleware(state=>state.nav,/*2.将根导航器组件传递给reduxifyNavigator函数并返回一个将navigationstate和dispatch函数作为props的新组件使用createReduxContainer方法,将RootNavigator封装成高阶组这个高阶组件完成了navigationprop的替换,改成了使用redux里的*constAppWithNavigationState=createReduxContainer(RootNavigator,//State到Props的映射constmapStateToProps=state{returnstate://使用Redux的connect函数再封装一个高阶组件,连接React组件与Reduxstoreexportdefaultconnect(mapStateToProps)(AppWithNavigationState);importimport{combineReducers}from"redux";importthemefrom"./theme";import ,RootNavigator}fromconstnavState /**上面的代码创建了一个导航action(表 打),那么我们就可以通过actionstate,通过方*法getStateForAction(action,*俩参数,一个是新的action,一个是当前的导航state,返回新的状态,当没有办法执行这个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=*创建exportdefaultcreateStore(reducers,importimportReact,{Component}from'react';import{Provider}from'react-redux';importAppNavigatorfromimportstorefromtypeProps=exportdefaultclassAppextends{render()*将store传递给App框return<Provider}}搞定 创建###Types.js###Types.jsexportdefault{THEM_CHANGE:"THEM_CHANGE",THEM_INIT:"THEM_INIT"创建importimportTypesfromexportfunctiononThemeChange(theme){return{type:Types.THEM_CHANGE,theme:theme}创建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发起请要从任意地址获取内容的话,只需简单地将作为参数传递给fetch方法即可(fetch这个词本身也就是获取的意思)Fetch还有可选的第二个参数,可以用来定制HTTP请求一些参数。你可以指定header参数,或是指定使用POST方法,又或是提交数据等等:{method:'POST',headers:{Accept:'application/json','Content-Type':'application/json',JSON.stringify({firstParam:'yourValue',secondParam:ars中的Content-TypeCtt-Typey的格式也有区别。到底应该采用什么样的Content-Type取决于服务器端,所以请和服务器下{method:'POST',headers:{'Content-Type':'application/x-www-form-body:Fetch方返回一个Promise,这种模式可以简化异步风格的代functionfunctiongetMoviesFromApiAsync(){returnfetch('.then((response)=>.then((responseJson){return.catch((error){ReactNativeES2017标准中的asyncawait语法注意这个方法前面有async关键asyncasyncfunction{try注意这里的await语句,其所在的函数必须有asyncletresponse=awaitfetch('letresponseJson=awaitresponse.json();returnresponseJson.movies;}catch{}}别忘了catch住fetch可能抛出的异常,否则出错时你可能看不到任何注意:使用Chrome调试目前无法观测到ReactNative中的网络请求,你可以使用第的react-重要,处理一的HTP状态码时,从ftch()的pomise不会被标记为eject该HTTP404或50。相反,它会将omiseveslveok属为fals被为eject。一次请求没有调用ejecteslve情况下,再判断sos.ktruletleturl=`http.then(response{if{return}thrownewError("Networkresponsewasnot.then(responseText{.catch(e{数据AsyncStorage是一个简单的、异步的、持久化的Key-Value系统,它对于App来说是全局性的。可用来代替LocalStorage。我们推荐您在AsyncStorage的基础上做一层抽象封装,而不是直接使用AsyncStorage在iOS上,AsyncStorage在原生端的实现是把较小值存放在序列化的字典中,而把较大值写入单独的文件。在Android上,AsyncStorage会尝试使用RocksDB,或退而选择。在新版本的RN中AS已经从RN框架中移除了,使用第库 async-storage来替代。安##$yarnmunity/async-#$react-nativemunity/async-使importimportAsyncStoragefrommunity/async-数asyncasyncerr&&err&&awaiterr&&}}数asyncasyncerr&&err&&constvalue=awaitAsyncStorage.getItem(Key)err&&}}删除数asyncasyncerr&&err&&awaiterr&&}}离线缓存有什么体的我制们线验。务户离线缓存有什么数据的实时性要求不高离线缓存的策优先从服务器获取数据,数据返回后同步到本地数据库,如果发生网络故障,才从本地获取数离线缓存框架的优先从本地实现思returnnewif(wrapdata&&DataStore.checkTimestampValid(wrapdata.timestamp)){}.catch(error{.then(data{.catch(error{}首先需要实现对数据的importimportAsyncStoragefrommunity/async-exportdefaultclassDataStore{saveData(url,data,callback){if(!data||!url)AsyncStorage.setItem(url,JSON.stringify(this._wrapData(data)),}}//上述代码url作为缓存数据的key,接受一个Object的参数data为value,因为AS是无法保存的,所以需要把它序列化成给离线的数据添加一个时间戳,便于计_wrapData_wrapData(data)return{data:data,timestamp:newDate().getTime()};////本地时间,推荐服务器间}获取本地数returnnewresolve(JSON.parse(result))//getItem获取到的是string为}}获取网络数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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论