1. 程式人生 > 實用技巧 >React Native 新增 Redux 支援

React Native 新增 Redux 支援

0x1 前言

之前寫的專案都是人家編寫好的腳手架,裡面包含專案所需的環境檔案,但由於有些東西用不到打包增加軟體體積,所以自己從頭搭建個環境。是基於 Native Base +react-navigation + Redux的reactNative腳手架,現在專案環境如下:

{
  "name": "app",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "native-base": "^2.13.4",
    "react": "16.8.6",
    "react-native": "0.60.5",
    "react-native-gesture-handler": "^1.3.0",
    "react-native-keyboard-aware-scroll-view": "^0.9.1",
    "react-native-reanimated": "^1.2.0",
    "react-navigation": "^3.11.1"
  },
  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/runtime": "^7.5.5",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-eslint": "7.2.3",
    "babel-jest": "^24.8.0",
    "eslint": "4.4.1",
    "eslint-plugin-flowtype": "2.35.0",
    "eslint-plugin-import": "2.7.0",
    "eslint-plugin-js
x-a11y": "6.0.2", "eslint-plugin-prettier": "2.1.2", "eslint-plugin-react": "7.1.0", "eslint-plugin-react-native": "3.0.1", "jest": "^24.8.0", "metro-react-native-babel-preset": "^0.56.0", "prettier": "1.5.3", "react-test-renderer": "16.8.6" }, "jest": { "preset": "react-native" } }

資源搜尋網站大全 https://www.renrenfan.com.cn 廣州VI設計公司https://www.houdianzi.com

0x2 新增 Redux 支援

這裡大概講解下安裝類庫支援:

yarn add yarn add react-navigation react-native-gesture-handler react-native-reanimated native-base

連結字型庫資源:

react-native link

react-navigation在 Android環境額外新增程式碼支援,具體情況文件:MainActivity.java

react-navigation在 react-native版本大於 0.60的時候不需要執行 react-native link連結。

由於專案需要狀態管理支援,故新增 Redux狀態管理類庫支援,在 React Native環境下和 React專案一樣:

yarn add redux react-redux redux-logger

redux-logger是監控狀態資料流日誌,可以在控制檯輸出狀態值的資訊。

由於專案基本環境是 Native Base環境,這裡怎麼安裝它就不再描述了,故在基礎專案下新增專案支援 Redux即可。開啟 ./src/App.js新增 Redux能力支援:

import {Root} from "native-base";
import {createStackNavigator, createAppContainer} from "react-navigation";
import {applyMiddleware, createStore} from "redux";
import {Provider} from "react-redux";
import React from "react";
import logger from "redux-logger";
import allReducers from "./store";
import reduxDemo from "./screens/reduxDemo";
 
const store = createStore(
  allReducers,
  applyMiddleware(logger)
); // 建立 Store
 
const AppNavigator = createStackNavigator(
  {
    ReduxDemo: {screen: reduxDemo},
  },
  {
    initialRouteName: "ReduxDemo", // 路由入口
    headerMode: "none", // 由於 react-navigation 預設導航欄自定義效果很差,故隱藏
  },
);
 
const AppContainer = createAppContainer(AppNavigator);
 
export default () => (
  <Provider store={store}>
    <Root>
      <AppContainer/>
    </Root>
  </Provider>
);

建立狀態觸發事件業務集 ./store/reducers/counter.js:

let count = 0;
export default function (state = count, action) {
  switch (action.type) {
    case "Increment":
      count++;
      break;
    case "Decrement":
      count--;
      break;
  }
  return count;
}

這裡是根據觸時不同條件要執行的業務,例如數字的增加和減少。假如專案下有很多觸發業務集合,我們需要把他們歸納一起,並且方便獲取狀態值獲取,新建 ./src/store/index.js:

import {combineReducers} from "redux";
import countReducer from "./reducers/counter";
 
const allReducers = combineReducers({
  count: countReducer,
});
export default allReducers;

然後需要有個動作器來觸發上面的業務,新建 ./src/store/actions/counter.js:

export function increment() {
  return {
    type: "Increment"
  };
}
 
export function decrement() {
  return {
    type: "Decrement"
  };
}

如果需要改動狀態值只能從上面的函式進行觸發,這是唯一入口。

下面就編寫頁面進行測試,新建 ./src/screens/reduxDemo/index.js:

import React, {Component} from "react";
import {Container, Content, Text, Card, Header, Body, Button, Title, CardItem} from "native-base";
import {increment, decrement} from "../../store/actions/counter";
import {bindActionCreators} from "redux";
import {connect} from "react-redux";
 
class Counter extends Component {
  render() {
    console.log(this.props.count);
    return (
      <Container>
        <Header>
          <Body>
            <Title>Redux 計數器</Title>
          </Body>
        </Header>
        <Content padder>
          <Card>
            <CardItem>
              <Text>
                {this.props.count}
              </Text>
            </CardItem>
          </Card>
          <Text/>
          <Button block onPress={() => this.props.increment()}>
            <Text>增加</Text>
          </Button>
          <Text/>
          <Button block onPress={() => this.props.decrement()}>
            <Text>減少</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}
 
function mapStateToProps(state) {
  return {
    count: state.count // 這裡等效於 prop.state 不過redux1幫你封裝好的
  };
}
 
function matchDispatchToProps(dispatch) {
  return bindActionCreators({increment: increment, decrement: decrement}, dispatch); // 繫結動作事件
}
 
export default connect(mapStateToProps, matchDispatchToProps)(Counter); // 連線Redux