使用TypeScript创建React Native

久未见 提交于 2021-02-13 14:05:52

⒈初始化 React Native环境

  参考https://reactnative.cn/docs/getting-started.html

⒉安装React Native官方的脚手架工具

npm install -g @react-native-community/cli

⒊使用React Native脚手架初始化项目

#默认是JavaScript
npx react-native init ts_react_native
#可以直接使用TypeScript初始化
npx react-native init ts_react_native --template react-native-template-typescript

 

⒋安装watchman

  watchman用于监控React Native项目中文件的变动,经常有开发者忘记安装watchman而导致项目无法启动的情况

cd ts_react_native
y watchman

⒌更改项目为TypeScript环境

  1.将TypeScript以及React Native和Jest的类型添加到您的项目中。

yarn add typescript @types/jest @types/react @types/react-native @types/react-test-renderer
# or for npm
npm install --save-dev @types/jest @types/react @types/react-native @types/react-test-renderer

  ⒉在项目的根目录中创建TypeScript配置文件tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

  3.创建一个jest.config.js文件来配置Jest以使用TypeScript

module.exports = {
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};

  4.重命名一个JavaScript文件为 *.tsx

  5.运行yarn tsc以检查新的TypeScript文件。

  6.启动项目

#启动ios
cd ts_react_native && npx react-native run-ios
#启动Android
cd ts_react_native && npx react-native run-android

⒍设计架构

  React Native的项目架构如图所示

  这与React App的常规架构几乎一摸一样,只是使用React Navigation作为路由库。

  我们必须充分利用代码复用的优势。在React Native中,我们同样需要使用Redux对状态进行全局管理。这样的结构是为了React生态能够简单地移植。

⒎React Navigation 

  React Navigation是React Native上的一个路由解决方案,它在进行设计的时候,很多函数都是以高阶函数的方式实现的,所以使用时会有很多不太直观的地方。

yarn add react-navigation @types/react-navigation

  将之前的index.tsx改名为List.tsx,因为后面需要实现列表页,然后再新建一个index.tsx

  

import React from 'react';
import {StackNavigator} from 'react-navigation';
import List from './List';

const StackRouter = StackNavigator({
  List:{
    screen:List
  }
},{
  initialRouteName: 'List',
})

const Router = () => (<StackRouter />)

expect default Router

  路由就算集成完毕了。

⒏Redux

  添加依赖后,修改相关代码。1.需要移除react-router相关代码,2要修改在开发环境下连接Redux开发工具的函数。

src/store/index.ts
import {applyMiddleware, combineReducers, createStore} from 'redux';
import {composeWithDevTools} from 'redux-devtools-extension';
import {persistReducer,persistStore,PersistConfig} from 'redux-persist';
import storage from 'redux-persist/es/storage';
import thunk from 'redux-thunk';
import reducers from '../reducer';

const middleware = [thunk];

const rootReducer = combineReducers({
  ...reducers,
})

const persistConfig: PersistConfig = {
  key: 'root',
  storage,
  whitelist: ['draft'],
}

const persistedReducer: typeof rootReducer = persistedReducer(PersistConfig,rootReducer);

const store = createStore(
  persistedReducer,
  __DEV__? composeWithDevTools(applyMiddleware(...middleware)) : applyMiddleware(...middleware),
)

const persistor = persistStore(store);

export{
  store,
  persistor,
}
src/index.tsx
import React from 'react';
import {StackNavigator} from 'react-navigation';
import List from './List';
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/integration/react';
import {persistor,store} from './store';

const StackRouter = StackNavigator({
  List:{
    screen:List
  }
},{
  initialRouteName: 'List',
})

const Router = () => (
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <StackRouter />
    </PersistGate>
  </Provider>
)

expect default Router

  这样,我们就能最大限度地复用React App中的代码了。

  *可以使用react-native-debugger进行调试

⒐列表页

  实现列表页需要连接Redux然后获取数据,这里我们先用Text组件来循环渲染

  这个地方需要注意,要全局修改网路请求的地址到localhost:3001,因为App上没有跨域的限制,可以直接访问。

  所以我们先发一波网络请求。

src/List.tsx
import React, { Component } from 'react';
import {Platform,StyleSheet,Text,View,TouchableOpacity} from 'react-native';
import {fetchList} from './action';
import {connect} from 'react-redux';

const mapStateToProps = (storeState,IStoreState) => ({
  list: storeState.list,
})

type IStateProps = ReturnType<typeof mapStateToProps>

const mapDispatchToProps = {
  fetchList,
}

type IDispatchProps = typeof mapDispatchToProps

type IProps = IStateProps & IDispatchProps

class App extends Component<IProps> {
  componentDidMount(){
    this.props.fetchList()
  }
  
  render(){
    console.log(this.props.list)
    return(
      <View style={styles.container}>

      </View>
    )
  }
}

export default connect<IStateProps,IDispatchProps>(mapStateToProps,mapDispatchToProps)(App)

const styles = StyleSheet.create({
  container:{
    flex:1,
    justifyContent:"center",
    alignItems:"center",
    backgroundColor:'#F5FCFF',
  },v
});

  在Debugger工具中你可以看到Action的变化,但不能看到网络请求。

  有个小技巧,在Dubugger中点击右键,选择Enable Network Inspect就可以在Network Tab页下查看网络请求了。

  到这里,你会发现所有的东西又回到了熟悉的React环境中。

⒑总结

  如果你熟悉React,那么就已经入门React Native一半了。

  如果了解在React下使用TypeScript,那么在React Native中使用React全家桶更是轻而易举。

  如果在React Native的开发中没有使用TypeScript,在没有严格类型检查的情况下,在React Native中,空值或者异常值会直接导致Native运行环境的奔溃,代码的质量把关比起Web环境要严苛了许多,这也是React Native项目最后必然都引入类型检查工具的原因。

  建议大家在创建React Native项目时,优先使用TypeSctipt,这可以避免很多由脏数据产生难以发觉的bug。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!