redux在react-native上使用(一)--加入redux

原始項目

[圖片上傳失敗...(image-312b62-1510626189352)]

這是非常簡單的一個項目, 就是一個計數(shù)器, 只有兩個文件package.jsonindex.ios.js, 點擊加1按鈕數(shù)字值就會+1, 點擊減1按鈕數(shù)字值就會-1, 點擊歸零按鈕則數(shù)字值置為0;

index.ios.js代碼:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';

class Main extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 5 }
  }

  _onPressReset() {
    this.setState({ count: 0 })
  }

  _onPressInc() {
    this.setState({ count: this.state.count+1 });
  }

  _onPressDec() {
    this.setState({ count: this.state.count-1 });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.counter}>{this.state.count}</Text>
        <TouchableOpacity style={styles.reset} onPress={()=>this._onPressReset()}>
          <Text>歸零</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.start} onPress={()=>this._onPressInc()}>
          <Text>加1</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.stop} onPress={()=>this._onPressDec()}>
          <Text>減1</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'column'
  },
  counter: {
    fontSize: 50,
    marginBottom: 70
  },
  reset: {
    margin: 10,
    backgroundColor: 'yellow'
  },
  start: {
    margin: 10,
    backgroundColor: 'yellow'
  },
  stop: {
    margin: 10,
    backgroundColor: 'yellow'
  }
})

AppRegistry.registerComponent('Helloworld', () => Main);

添加redux

先添加redux相關(guān)依賴庫, 在package.json里添加三個庫并在目錄下npm install:

"dependencies": {
    ...
    "react-redux": "^4.4.5",
    "redux": "^3.5.2",
    "redux-logger": "^2.6.1"
},

再創(chuàng)建actionsTypes.js用來定義所有的action名稱, 定義三個action, 一個增加, 一個減小, 一個重置:

export const INCREASE = 'INCREASE';
export const DECREASE = 'DECREASE';
export const RESET = 'RESET';

創(chuàng)建actions.js, 在里面創(chuàng)建三個action:

import { INCREASE, DECREASE, RESET } from './actionsTypes';

const increase = () => ({ type: INCREASE });
const decrease = () => ({ type: DECREASE });
const reset = () => ({ type: RESET });

export {
    increase,
    decrease,
    reset
}

創(chuàng)建reducers.js, 根據(jù)需要在收到相關(guān)的action時操作項目的state:

import { combineReducers } from 'redux';
import { INCREASE, DECREASE, RESET} from './actionsTypes';

// 原始默認(rèn)state
const defaultState = {
  count: 5,
  factor: 1
}

function counter(state = defaultState, action) {
  switch (action.type) {
    case INCREASE:
      return { ...state, count: state.count + state.factor };
    case DECREASE:
      return { ...state, count: state.count - state.factor };
    case RESET:
      return { ...state, count: 0 };
    default:
      return state;
  }
}

export default combineReducers({
    counter
});

創(chuàng)建store.js:

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

const configureStore = preloadedState => {
    return createStore (
        rootReducer,
        preloadedState,
        compose (
            applyMiddleware(createLogger)
        )
    );
}

const store = configureStore();

export default store;

至此redux的幾大部分都創(chuàng)建完畢, 下一步就是引入項目中. 創(chuàng)建app.jshome.js.

index.ios.js更改:

import { AppRegistry } from 'react-native';
import App from './app';

AppRegistry.registerComponent('Helloworld', () => App);

app.js

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>
    );
  }
}

home.js在原來index.ios.js的代碼上修改成如下:

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';
import { connect } from 'react-redux';
import { increase, decrease, reset } from './actions';

class Home extends Component {
  _onPressReset() {
    this.props.dispatch(reset());
  }

  _onPressInc() {
    this.props.dispatch(increase());
  }

  _onPressDec() {
    this.props.dispatch(decrease());
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.counter}>{this.props.counter.count}</Text>
        <TouchableOpacity style={styles.reset} onPress={()=>this._onPressReset()}>
          <Text>歸零</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.start} onPress={()=>this._onPressInc()}>
          <Text>加1</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.stop} onPress={()=>this._onPressDec()}>
          <Text>減1</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  ...
})

const mapStateToProps = state => ({
    counter: state.counter
})

export default connect(mapStateToProps)(Home);

OK, 大功告成, commond+R運行, command+D打開chrome瀏覽器調(diào)試, 可以看到redux-logger把每個action動作都打和state的前后變化印出來了,非常直觀方便.

chrome log
最后編輯于
?著作權(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)容