使用taro开发小程序时,初始化小程序
taro init myApp
选择redux组件。
可以看到redux中, store.js里使用的是redux-thunk管理异步
import { createStore, applyMiddleware, compose } from 'redux'
import thunkMiddleware from 'redux-thunk'
import rootReducer from '../reducers'
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
const middlewares = [
thunkMiddleware
]
if (process.env.NODE_ENV === 'development') {
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)
return store
}
就将以上修改一下换成redux-saga
import { createStore, applyMiddleware, compose } from 'redux';
import createSagaMiddleware, { END } from 'redux-saga';
import rootReducer from '../reducers/index';
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
export default function configStore() {
const sagamiddleware = createSagaMiddleware();
const middlewares = [
sagamiddleware
]
if (process.env.NODE_ENV === 'development') {
middlewares.push(require('redux-logger').createLogger());
}
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(...middlewares)));
store.runSaga = sagamiddleware.run
store.close = () => store.dispatch(END)
return store
}
同时修改app.js
import '@tarojs/async-await'
import Taro, { Component } from '@tarojs/taro'
import { Provider } from '@tarojs/redux'
import Index from './pages/index'
import configStore from './redux/store'
import rootSaga from './redux/sagas/index'
import './style/custom-theme.scss'
import './style/app.less'
import './style/taro-ui.css'
const store = configStore()
// 注入saga
store.runSaga(rootSaga)
class App extends Component {
// 在 App 类中的 render() 函数没有实际作用
// 请勿修改此函数
render() {
return (
<Provider store={store}>
<Index />
</Provider>
)
}
}
Taro.render(<App />, document.getElementById('app'))
import rootSaga from ‘./redux/sagas/index’ 如下
import createSagaMiddleware from 'redux-saga'
import { all, call, fork, takeEvery } from 'redux-saga/effects'
import { request } from './com/request'
export default function* rootSaga() {
yield all([
// 监听请求中
takeEvery('REQUESTING', request)
])
}
saga异步管理
import { call, put } from 'redux-saga/effects'
import { REQUEST, REQUESTING, REQUEST_SUCCESS, REQUEST_ERROR } from '../../constants/request'
// eslint-disable-next-line import/prefer-default-export
export function* request(action) {
try {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(21321)
console.log('pppppppppppppppppppppp')
}, 2000)
})
const p = function () {
return promise.then(res => {
return res
})
}
let res = yield call(p)
yield put({ type: REQUEST_SUCCESS, data: p })
return action;
} catch (error) {
// yield put({type: REQUEST_ERROR});
}
}
combineReducers
import { combineReducers } from 'redux';
import request from './com/request';
export default combineReducers({
requestReducer: request
});
reducer.js
import { REQUEST, REQUESTING, REQUEST_SUCCESS, REQUEST_ERROR } from '../../constants/request';
let INITIAL_STATE = {
type: REQUEST
}
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case REQUESTING:
return {
type: REQUESTING,
}
case REQUEST_ERROR:
return {
type: REQUEST_ERROR,
}
case REQUEST_SUCCESS:
return {
type: REQUEST_SUCCESS,
data: action.data,
}
default:
return {
type: REQUEST,
}
}
}
actions.js
import { REQUEST, REQUESTING, REQUEST_SUCCESS, REQUEST_ERROR } from '../constants/request';
export const request = () => {
return {
type: REQUEST
};
}
export const requesting = () => {
return {
type: REQUESTING
}
}
export const requestSuccess = (data) => {
return {
type: REQUEST_SUCCESS,
data
}
}
export const requestError = (data) => {
return {
type: REQUEST_ERROR,
data
}
}
constants/request.js
// 请求
export const REQUEST = 'REQUEST'
export const REQUESTING = 'REQUESTING'
export const REQUEST_SUCCESS = 'REQUEST_SUCCESS'
export const REQUEST_ERROR = 'REQUEST_ERROR'
如上一个异步状态管理配置完成
页面触发aciton
import Taro, { Component } from '@tarojs/taro'
import { View, Button, Text, Swiper, SwiperItem, Image } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { bindActionCreators } from 'redux'
import { AtButton } from 'taro-ui'
import { request, requesting, requestSuccess } from '../../redux/actions/request'
import { firstRquest } from '../../api/index/fetch'
import './index.less'
class Index extends Component {
config = {
navigationBarTitleText: '首页',
}
componentWillReceiveProps(nextProps) {
console.log(this.props, nextProps)
}
componentWillUnmount() { }
componentDidShow() { }
componentDidHide() { }
startRequest() {
this.props.request()
firstRquest().then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
startRequesting() {
this.props.requesting()
}
endRequest() {
this.props.requestSuccess('success')
}
toDetails() {
Taro.navigateTo({ url: '/pages/subpackages/details/index' })
}
render() {
return (
<View className="container">
<View className="panel">
<View className="title">新品推荐</View>
<View>{this.props.requestReducer.type}</View>
<Button onClick={() => this.startRequest()}>开始request</Button>
<Button onClick={() => this.startRequesting()}>requesting</Button>
<Button onClick={() => this.endRequest()}>结束request</Button>
<AtButton type='primary' size='normal' onClick={() => this.toDetails()}>uiuuui</AtButton>
</View>
</View>
)
}
}
const mapStateToProps = (state) => {
return {
requestReducer: state.requestReducer,
}
}
const mapDispatchToProps = (dispatch) => {
return {
request: bindActionCreators(request, dispatch),
// 点击调用requesting 进入saga异步管理
requesting: bindActionCreators(requesting, dispatch),
requestSuccess: bindActionCreators(requestSuccess, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Index)