一款輕閱讀應用ReadIT,記錄我的RN躺坑之旅

dapan發表於2021-09-09

背景

一款輕閱讀應用ReadIT,支援功能:優質文章推送、評論點贊、計劃制定、計劃鬧鐘、天氣預報、收藏文章、深淺兩套主題、多語言切換、極光推送等功能。後續還會繼續整合功能。前後端均自主研發,借鑑市面較好的種子工程,目前未上應用市場,文章目前也比較少,後續會持續補充優質文章。

展示效果

點我

下載體驗(目前只有安卓版)

img

Github

https://github.com/xiaobinwu/readIt

技能樹

1、客戶端(react-native、@react-navigation、react-native第三方庫、typescript、mobx、marked等技術)

2、中臺後管系統(antd4、react、redux、react-router4、hook等技術)

3、後端程式(koa、mongoDb、jsonwebtoken、ali-oss等技術)

react-devtools除錯(安卓模擬器)

1、開發者選單中選擇"Debug JS Remotely"選項
2、自動開啟除錯頁面 http://localhost:8081/debugger-ui(可做斷點除錯)
3、開啟有異常時暫停(Pause On Caught Exceptions)選項,能夠獲得更好的開發體驗
4、設定環境變數ELECTRON_MIRROR='https://npm.taobao.org/mirrors/electron/',防止下載react-devtool卡住
5、安裝react-devtools,package.json配置npm script,執行npm run react-devtools
6、執行adb reverse tcp:8097 tcp:8097
7、目前react-native => 0.61.5,react-devtool => 3.6.3
8、參考資料:參考資料

注意:react-devtools v4 需要 react-native 0.62 或更高版本才能正常工作。一升級就報錯,後續跟進

iconfont字型圖示使用

1、下載Iconfont字型圖示專案,下載至本地,獲取iconfont.ttf
2、放至src/assets/fonts目錄
3、配置react-native.config.js,參考資料,如下:

    module.exports = {
        project: {
            ios: {},
            android: {}, // grouped into "project"
        },
        assets: ["./src/assets/fonts/"], // stays the same
    };

4、執行npm run link,將對應iconfont.ttf分別新增至iOSInfo.plistFonts provided by application下新增一行iconfont.ttf)、Android(複製至app/src/main/assets/fonts資料夾中,並且app/src/build.gradle新增配置)
5、將iconfont.json複製至src/components/common/iconfont
6、字型圖示封裝可參考第4步目錄相對應元件檔案
7、參考資料:參考資料

tsconfig.json配置

1、詳細各個配置項解析,可檢視tsconfig.json
2、配置paths,結果不起效,需在src目錄新增package.json,配置如下

{
  "name": "@app"
}

第三方庫

1、autobind-decorator => 自動將方法繫結到類例項,針對babel7需額外配置外掛,如下:

    {
      plugins:  ["@babel/plugin-proposal-decorators", { legacy: true }]
    }

2、mobx / mobx-react => 簡單、可擴充套件的狀態管理,前往
3、@react-navigation/bottom-tabs / @react-navigation/native / @react-navigation/stack => 跨平臺導航方案,前往
4、react-native-appearance => 在iOS,Android和Web上訪問作業系統外觀資訊。目前支援檢測首選配色方案(淺色/深色),前往
5、react-native-localize => 用於React Native應用本地化的工具箱,前往
6、@react-native-community/async-storage => 簡單的、非同步的、持久化的 Key-Value 儲存系統,前往
7、react-native-actionsheet => 跨平臺ActionSheet,前往
8、react-native-webview => WebView,旨在替代內建WebView,前往
9、marked => markdown編譯器,前往
10、highlight.js => 程式碼高亮工具,前往
11、react-native-autoheight-webview => React Native的自動高度webview,前往
12、react-native-image-viewing => 圖片滑動瀏覽控制元件,前往
13、react-native-root-toast => 吐司控制元件,前往
14、react-native-calendars => 日曆,前往
15、jcore-react-nativejpush-react-native => 極光推送
16、react-native-alarm-clock => 鬧鐘,前往
17、react-native-amap-geolocation => 高德地址服務,前往
18、 react-native-device-info => 獲取裝置資訊,前往
19、 react-native-image-picker => 上傳圖片,前往
20、react-native-modal-datetime-picker => 時間選擇器,前往
21、react-native-picker-select => 下拉框選擇器,前往
22、react-native-splash-screen => 應用啟動圖,前往

第三方庫躺坑

如何獲取當前天氣、未來三天天氣?

使用的是和風天氣API,需要經緯入參,所以必須先獲取位置,需要申請和風天氣的appKey。

推送服務

極光推送服務 jcore-react-nativejpush-react-native,需要申請AppKey。

如何獲取位置?

Part1,使用react-native-geolocation-service第三方庫,獲取經緯度進行高德逆地理編碼API呼叫,獲取城市,開啟google play服務,需要有處理獲取位置的服務程式app/services/location(參考react-native-geolocation-service github example),以及修改android/app/src/main/AndroidManifest.xml,新增<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 安卓新增許可權。結果不行,針對google play服務國內不能使用,所以該方案得摒棄掉,對應app/services/location會刪除。

Part2,使用react-native-amap-geolocation第三方庫,介面文件使用指南

圖片上傳問題

對於react-native-image-picker第三方庫, 對於3.1.4版本,minSdkVersion最少要21以上,在使用的react-native 0.61.5下,修改android/build.gradleminSdkVersion配置

阿里oss aliyun-oss-rn,需要更改aliyun-oss-rn npm包的android/build.gradle(如下配置),提高SDK版本號,以及修改主專案AndroidManifest.xml,新增android:allowBackup="true",目前使用上仍有問題,於是放棄該方案,改用oss postObject直傳方式,參考資料,使用sts臨時授權、policy、Signature配合上傳。

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1'
    }
}

apply plugin: 'com.android.library'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
    }
    lintOptions {
        abortOnError false
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.facebook.react:react-native:+'
    implementation 'com.aliyun.dpa:oss-android-sdk:+'
}
  
  

日曆問題

react-native-calendarsAgenda問題如下:
一、國際化切換、主題切換時,日曆沒有對應切換,對應HACK處理方法,給Agenda元件設定key,強制元件解除安裝,重新載入
二、Agenda在國際化切換、主題切換、新增日程的時候,會導致Agenda元件內部View元件onLayout重複觸發(我是不需要其一直觸發),導致this.viewHeight一直髮生變化,導致每次動畫執行定位不准問題,處理方法,用個變數儲存this.viewHeight,示例程式碼如下:

let VIEW_HEIGHT = 0;

constructor(props) {
    this.viewHeight = VIEW_HEIGHT || windowSize.height;
}

onLayout = event => {
    if (!VIEW_HEIGHT) {
        VIEW_HEIGHT = event.nativeEvent.layout.height;
        this.viewHeight = event.nativeEvent.layout.height;
        this.viewWidth = event.nativeEvent.layout.width;
        this.forceUpdate();
    }
};

三、日程列表改造,只顯示當前選中日期的的日程,Agenda元件程式碼改造如下:


  renderReservations() {
    const reservationListProps = extractComponentProps(ReservationList, this.props);
    let reservations = {};
    const { items } = this.props;
    if (this.props.selected && items[this.props.selected.dateString]) {
      reservations = { [this.props.selected.dateString]: items[this.props.selected.dateString] };
    }
    console.log(this.props.selected, '選中的時間');

    return (
      <ReservationList
        {...reservationListProps}
        ref={c => (this.list = c)}
        reservations={reservations}
        selectedDay={this.state.selectedDay}
        topDay={this.state.topDay}
        onDayChange={this.onDayChange}
        onScroll={() => {}}
      />
    );
  }


鬧鐘問題

react-native-alarm-clock,目前yarn、npm均不能下載1.0.0,只能將2.0.0版本下載至本地,替換node_moudules中的對應npm包,功能使用還未考證,仍有問題。

選擇下拉框問題

react-native-picker-select,報錯資訊 "RNCAndroidDialogPicker" was not found in the UIManager,參考Issues,解決辦法,降級@react-native-picker/picker1.8.3

打包 APK 問題

管理員CMD,參考

#keytool -genkey -dname "CN=wushaobin,OU=個人,O=個人,L=深圳,ST=廣東,C=CN" -alias test -keyalg RSA -validity 400000 -keystore test.keystore  
#keytool -importkeystore -srckeystore test.keystore -destkeystore test.keystore -deststoretype pkcs12  
#keytool -list -v -keystore test.keystore -storepass xxxxxxxxx  
或 keytool -genkeypair -v -keystore test.keystore -alias test -keyalg RSA -keysize 2048 -validity 400000  

app應用啟動圖

1、下載react-native-splash-screen

2、android/app/src/main/java/com/readit/MainActivity.java,配置如下:

import com.facebook.react.ReactActivity;

+ import org.devio.rn.splashscreen.SplashScreen;
+ import android.os.Bundle;

public class MainActivity extends ReactActivity {

  /**
@@ -12,4 +15,11 @@
  protected String getMainComponentName() {
    return "readIt";
  }

  // 新增下面方法
  + @Override
  + protected void onCreate(Bundle savedInstanceState) {
      + SplashScreen.show(this);  // here
      + super.onCreate(savedInstanceState);
  + }
}

3、android/app/src/main/res/layout/launch_screen.xml配置如下(沒有就新增):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
    <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/launch_screen" android:scaleType="centerCrop" />
</LinearLayout> 

4、android/app/src/main/res/values/styles.xml配置如下:

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:textColor">#000000</item>
        + <!--新增這一行-->
        + <item name="android:windowIsTranslucent">true</item>
    </style>

5、使用如下:

import SplashScreen from 'react-native-splash-screen';

...

componentDidMount() {
    SplashScreen.hide();
}


app應用圖示問題

替換android/app/src/main/res/mipmap-*資料夾中圖示圖片

./gradlew assembleRelease失敗問題
1、先執行./gradlew clean,解除安裝上一個debug版本
2、再執行./gradlew assembleRelease,生成release版本

常用指令 ./gradlew clean./gradlew build

編譯錯誤:The Kotlin Gradle plugin was loaded multiple times in different subprojects, which is not supported and may break the build. 問題解決方案:

參考: https://forums.expo.io/t/kotlin-error-when-build-or-install/38868

./gradlew assembleRelease 編譯失敗

失敗資訊: Error: ENOENT: no such file or directory, open 'F:\Project\reactnative\readIt\android\app\build\generated\sourcemaps\react\release\index.android.bundle.map'

問題解決方案:
參考: https://stackoverflow.com/questions/56808518/android-gradlew-assemblerelease-sourcemap-output-fail-because-bundle-doesnt-e

釋出版本時,刪除build/debug.apk,執行./gradlew clean

React Native Android9.0以上打包apk後http請求不到解決方法

參考資料

相關文章