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

原始項目

需求

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

index.ios.js代碼:ios

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相關依賴庫, 在package.json裏添加三個庫並在目錄下npm install:chrome

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

再建立actionsTypes.js用來定義全部的action名稱, 定義三個action, 一個增長, 一個減少, 一個重置:npm

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

建立actions.js, 在裏面建立三個action:json

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

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

export {
    increase,
    decrease,
    reset
}

建立reducers.js, 根據須要在收到相關的action時操做項目的state:redux

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

// 原始默認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
});

建立store.js:react-native

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的幾大部分都建立完畢, 下一步就是引入項目中. 建立app.jshome.js.瀏覽器

index.ios.js更改:app

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

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

app.jside

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瀏覽器調試, 能夠看到redux-logger把每一個action動做都打和state的先後變化印出來了,很是直觀方便.

chrome log

相關文章
相關標籤/搜索