taro中集成redux-saga

taro中redux處理方案是採用redux-thunk,這裏採用redux-saga解決異步問題,引入目前最新[email protected]

引入方式一

可以直接下載種子項目,已經引入了saga,並做好了相關配置,可在此基礎上再次開發
taro-redux-saga-seed

// 下載種子項目
git clone https://github.com/Z-HNAN/taro-redux-saga-seed

// 安裝依賴
cd taro-redux-saga-seed
npm i 

// 啓動項目-小程序(微信開發者工具查看效果,有一個3s延遲的add示例)
npm run dev:weapp

引入方式二

在自己已經有的項目上引入,按照後續步驟自行引入即可

安裝redux-saga

npm i redux-saga

更改目錄形式

將每個文件放在模塊中,利於查找,便於引入,後面引入saga文件也比較清晰,當然這裏只是一個個人喜好,也可按照自己的目錄形式來安排,這裏只做一個參考,請多留意引入文件路徑是否正確。

└─src                     
    │  app.jsx            
    │  app.less           
    │  index.html         
    │                     
    ├─pages               
    │  └─index            
    │          action.js  
    │          index.jsx  
    │          index.less 
    │          reducer.js 
    |          saga.js
    │                     
    └─store               
            index.js      
            reducer.js
            saga.js    

引入index模塊的saga

  • pages/index/saga.js捕獲當前模塊中的action
import { put, delay, takeEvery} from 'redux-saga/effects'

function* asyncAddRequest (action) {
  const { timeout } = action.payload
  yield delay(timeout)
  yield put({ type: 'ADD' })
}

export default function* () {
  yield takeEvery('ASYNC_ADD', asyncAddRequest)
}

配置根saga文件

  • store/saga.js啓動各個模塊的saga
import { all } from 'redux-saga/effects'

import index from '../pages/index/saga'

export default function* () {
  yield all([
    index()
  ])
}

在store中引入sagaMiddleware

  • store/index.jssaga連接到store
    • 引入saga
    • 配置saga中間件到middlewares
    • 啓動saga
import { createStore, applyMiddleware, compose } from 'redux'
/* 引入saga */
import createSagaMiddleware from 'redux-saga'
import rootSaga from './saga'
import rootReducer from './reducer'

const composeEnhancers =
  typeof window === 'object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
      // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
    }) : compose

/* 生成sagaMiddleware */
const sagaMiddleware = createSagaMiddleware();

const middlewares = [
  /* 應用saga */
  sagaMiddleware
]

/* 處理redux-logger */
if (process.env.NODE_ENV === 'development' && process.env.TARO_ENV !== 'quickapp') {
  middlewares.push(require('redux-logger').createLogger())
}

const enhancer = composeEnhancers(
  applyMiddleware(...middlewares),
  // other store enhancers if any
)

export default function configStore () {
  const store = createStore(rootReducer, enhancer)
  /* 啓動saga */
  sagaMiddleware.run(rootSaga)
  return store
}

檢測

  • pages/index/index.jsx 本例以taro的redux爲基礎進行測試
import Taro, { Component } from '@tarojs/taro'
import { View, Button, Text } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import { add, minus, asyncAdd } from './action'

import './index.less'

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

const mapDispatchToProps = (dispatch) => {
  return {
    add: () => {
      dispatch(add())
    },
    asyncAdd: () => {
      dispatch(asyncAdd({ timeout: 3000 }))
    },
    minus: () => {
      dispatch(minus())
    }
  }
}

@connect(mapStateToProps, mapDispatchToProps)
class Index extends Component {

    config = {
    navigationBarTitleText: '首頁'
  }

  componentWillReceiveProps (nextProps) {
    // console.log(this.props, nextProps)
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  render () {
    return (
      <View className='index'>
        <Button className='add_btn' onClick={this.props.add}>+</Button>
        <Button className='dec_btn' onClick={this.props.minus}>-</Button>
        <Button className='dec_btn' onClick={this.props.asyncAdd}>async</Button>
        <View><Text>{this.props.counter}</Text></View>
        <View><Text>Hello, Redux-saga</Text></View>
      </View>
    )
  }
}

export default Index

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章