wepy中使用redux-saga作為非同步中介軟體
依賴安裝 redux redux-saga wepy-redux
store/index.js
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga/dist/redux-saga'
import rootReducer from './reducers'
import rootSaga from './saga'
const sagaMiddleware = createSagaMiddleware()
const initState = {
global: {
list: [],
loading: true,
},
}
const store = createStore(rootReducer, initState, applyMiddleware(sagaMiddleware))
sagaMiddleware.run(rootSaga)
export default store
store/saga.js
import { effects } from 'redux-saga/dist/redux-saga'
import { getData } from './api'
const { call, put, takeLatest } = effects
function* fetchData({ payload }) {
yield put({
type: 'TOGGLELOADING',
payload: true,
})
try {
const data = yield call(getData, {})
yield put({
type: 'SETDATA',
payload: data,
})
yield put({
type: 'TOGGLELOADING',
payload: false,
})
} catch (e) {
console.log(e)
}
}
export default function* rootSaga() {
yield takeLatest('GETDATA', fetchData)
}
store/reducer/index.js
import { combineReducers } from 'redux'
function global(state = {}, action) {
switch (action.type) {
case 'SETDATA':
return { ...state, list: action.payload }
case 'TOGGLELOADING':
return { ...state, loading: action.payload }
default:
return state
}
}
const rootReducer = combineReducers({
global
})
export default rootReducer
頁面呼叫action: store.dispath({})