React Native Typescript Redux快速搭建

使用Visual Studio Code和typescript 開發(fā)調(diào)試React Native項目 之后,這次我們繼續(xù) React Native Typescript 系列

項目初始化的細(xì)節(jié)就不一一敘述的,感興趣的同學(xué)可以看下上面兩篇博客,我把最終代碼放到了 我的github倉庫上,里面有每個步驟的修改的代碼記錄。

原來的樣子

首先我們修改我們的src/index.tsx 實現(xiàn)一個簡單的計數(shù)器 代碼如下

import React, { Component } from "react";
import {
    StyleSheet,
    Text,
    View,
    Button,
    Platform
} from "react-native";
interface Props {
}
interface State {
    count:number;
}
const instructions = Platform.select({
    ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
    android:
      'Double tap R on your keyboard to reload,\n' +
      'Shake or press menu button for dev menu',
  });
export default class App extends Component<Props, State> {
    constructor(props:Props)
    { 
        super(props);
        this.state={count:0};
       
    }
    add = ()=>{

        this.setState({count:this.state.count+1})
    };
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>Welcome to React Native&typescript!</Text>
                <Text style={styles.instructions}>To get started, edit src/App.js</Text>
                <Text style={styles.instructions}>{instructions}</Text>
                <Text style={styles.instructions}>{this.state.count}</Text>
                <Button  onPress={this.add}  title="add" ></Button>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: '#F5FCFF',
    },
    welcome: {
      fontSize: 20,
      textAlign: 'center',
      margin: 10,
    },
    instructions: {
      textAlign: 'center',
      color: '#333333',
      marginBottom: 5,
    },
  });

開始redux

接下來我們按照Redux管理React數(shù)據(jù)流實現(xiàn)代碼
在開始之前我們學(xué)習(xí)下Redux


react-native-typescript-redux-201877184819

在圖中,使用Redux管理React數(shù)據(jù)流的過程如圖所示,Store作為唯一的state樹,管理所有組件的state。組件所有的行為通過Actions來觸發(fā),然后Action更新Store中的state,Store根據(jù)state的變化同步更新React視圖組件。
需要注意的是:
在主入口文件index.tsx中,通過Provider標(biāo)簽把Store和視圖綁定:

<Provider store={store}>
    //項目代碼
</Provider>

actions

指全局發(fā)布的動作指令,主要就是定義所有事件行為的

首先聲明定義 actionsTypes
actionsTypes.ts

export const ADD ="ADD";

新建actions.ts

import {ADD} from './actionsTypes';

const add=()=>({type:ADD})
export {
    add
}

reducers

Store是如何具體管理State呢?實際上是通過Reducers根據(jù)不同的Action.type來更新不同的state,即(previousState,action) => newState。最后利用Redux提供的函數(shù)combineReducers將所有的Reducer進(jìn)行合并,更新整個State樹

會用到的state類型
statesTypes.ts

export class CounterState{
    count:number
}

新建reducers.ts

import { combineReducers } from 'redux';
import {ADD} from './actionsTypes';
import {CounterState} from './statesTypes';

const defaultState={
    count:0
} as CounterState;
function counter(state=defaultState,action:any){
switch (action.type) {
    case ADD:
        return {...state,count:state.count+1};
    default:
        return state;
}
}
export default combineReducers({
    counter:counter
});

store

在 Redux 應(yīng)用中,只允許有一個 store 對象,管理應(yīng)用的 state.可以理解為一個存放APP內(nèi)所有組件的state的倉庫.
可以通過 combineReducers(reducers) 來實現(xiàn)對 state 管理的邏輯劃分(多個 reducer)。

新建store.ts

import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from './reducers';

const store=createStore(rootReducer);
export default store;

Provider

Provider 本身并沒有做很多事情,只是把 store放在 context 里罷了,本質(zhì)上 Provider 就是給 connect 提供 store 用的。

新建index.tsx

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import Home from './home';
import store from './store';

export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Home/>
      </Provider>
    );
  }
}

Container

利用Container容器組件作為橋梁,將React組件和Redux管理的數(shù)據(jù)流聯(lián)系起來。Container通過connect函數(shù)將Redux的state和action轉(zhuǎn)化成展示組件即React組件所需的Props。

新建home.tsx

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Button,
  Platform
} from 'react-native';
import { connect, DispatchProp } from 'react-redux';
import { add } from './actions';
import {CounterState} from './statesTypes';

interface State {
}
type Props=CounterState&DispatchProp
const instructions = Platform.select({
    ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
    android:
      'Double tap R on your keyboard to reload,\n' +
      'Shake or press menu button for dev menu',
  });
class Home extends Component<Props, State> {
    constructor(props:Props)
    {
        super(props);
    }
    _add = ()=>{

        this.props.dispatch(add())
    };
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>Welcome to React Native&typescript!</Text>
                <Text style={styles.instructions}>To get started, edit src/App.js</Text>
                <Text style={styles.instructions}>{instructions}</Text>
                <Text style={styles.instructions}>{this.props.count}</Text>
                <Button  onPress={this._add}  title="add" ></Button>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: '#F5FCFF',
    },
    welcome: {
      fontSize: 20,
      textAlign: 'center',
      margin: 10,
    },
    instructions: {
      textAlign: 'center',
      color: '#333333',
      marginBottom: 5,
    },
  });

  const mapStateToProps = (state:any) => (
    state.counter
)

export default connect(mapStateToProps)(Home);

最終代碼在 https://github.com/YahuiWong/react-native-typescript/tree/114aefbd3fbb96f9c67db068b340b908ed54276d
可在線查看

如果覺得有用,請Star ,謝謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容