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

在上一篇 redux在react-native上使用(一)--加入redux 已成功把redux添加到項目, 現(xiàn)在再把redux-saga添加進來.

這篇 redux在react-native上使用(三)--加入redux-thunk 是使用redux-thunk, 可以跟這篇做個對比看下redux-thunkredux-saga使用上的區(qū)別.

跑秒器
跑秒器

這一次做個跑秒器. 點擊開始按鈕就開始跑秒,點擊停止按鈕停止跑秒, 點擊重置按鈕時間就清零. 跑秒狀態(tài)下數(shù)字為藍色,停止狀態(tài)下為黑色.

先在package.json里添加redux-saga庫, 并在目錄下npm install:

"dependencies": {
    ...
    "redux-saga": "^0.11.0"
},

action名字改得更有意義點, actionsTypes.js:

export const START = 'START';
export const STOP = 'STOP';
export const RESET = 'RESET';
export const RUN_TIMER = 'RUN_TIMER';

actions.js跟著改:

import { START, STOP, RESET, RUN_TIMER } from './actionsTypes';

const start = () => ({ type: START });
const stop = () => ({ type: STOP });
const reset = () => ({ type: RESET });
const runTime = () => ({ type: RUN_TIMER });

export {
    start,
    stop,
    reset,
    runTime
}

reducers.jsaction改變后也需要調(diào)整:

import { combineReducers } from 'redux';
import { START, STOP, RESET, RUN_TIMER } from './actionsTypes';

// 原始默認state
const defaultState = {
  seconds: 0,
  runStatus: false
}

function timer(state = defaultState, action) {
  switch (action.type) {
    case START:
      return { ...state, runStatus: true };
    case STOP:
      return { ...state, runStatus: false };
    case RESET:
      return { ...state, seconds: 0 };
    case RUN_TIMER:
      return { ...state, seconds: state.seconds + 1 };
    default:
      return state;
  }
}

export default combineReducers({
    timer
});

添加一個sagas.js文件, 處理項目的業(yè)務邏輯:

import { takeEvery, delay, END } from 'redux-saga';
import { put, call, take, fork, cancel, cancelled } from 'redux-saga/effects';
import { START, STOP, RESET, RUN_TIMER } from './actionsTypes';
import { stop, runTime } from './actions';

function* watchStart() {
  // 一般用while循環(huán)替代 takeEvery
  while (true) {
    // take: 等待 dispatch 匹配某個 action
    yield take(START);
    // 通常fork 和 cancel配合使用,實現(xiàn)非阻塞任務,take是阻塞狀態(tài),也就是實現(xiàn)執(zhí)行take時候,無法向下繼續(xù)執(zhí)行,fork是非阻塞的,同樣可以使用cancel取消一個fork 任務
    var runTimeTask = yield fork(timer);
    yield take(STOP);
    // cancel: 取消一個fork任務
    yield cancel(runTimeTask);
  }
}

function* watchReset() {
  while (true) {
    yield take(RESET)
    yield put(stop());
  }
}

function* timer() {
  try {
    while(true) {
      // call: 有阻塞地調(diào)用 saga 或者返回 promise 的函數(shù),只在觸發(fā)某個動作
      yield call(delay, 1000);
      // put: 觸發(fā)某個action, 作用和dispatch相同
      yield put(runTime());
    }
  } finally {
    if (yield cancelled()) {
      console.log('取消了runTimeTask任務');
    }
  }
}


export default function* rootSaga() {
    yield fork(watchStart);
    yield fork(watchReset)
}

saga作為中間件添加進store, store.js如下:

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

const configureStore = preloadedState => {
    const sagaMiddleware = createSagaMiddleware();
    const store = createStore(
        rootReducer,
        preloadedState,
        compose (
            applyMiddleware(sagaMiddleware, createLogger())
        )
    )

    sagaMiddleware.run(sagas);
    store.close = () => store.dispatch(END);
    return store;
}

const store = configureStore();
export default store;

home.js修改下:

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

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

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

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

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.counter}>{this.props.timer.seconds}</Text>
        <TouchableOpacity style={styles.reset} onPress={()=>this._onPressReset()}>
          <Text>重置</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.start} onPress={()=>this._onPressInc()}>
          <Text>開始</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.stop} onPress={()=>this._onPressDec()}>
          <Text>停止</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

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

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

export default connect(mapStateToProps)(Home);

OK, 大功告成, commond+R運行.

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

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

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