redux-sagas的学习
2020-03-13 本文已影响0人
都江堰古巨基
redux-sagas个人的理解应该就是一个中间件,在执行dispatch之前执行的钩子函数,我们可以这样使用它,在一个功能中dispatch主要用于更改UI的值,但这个值需要去某个api获取,所以我们需要先获取到这个值,然后再进行更改,redux-sagas就用于获取这个值的过程。
项目的整体结构如下:
项目结构.png
在引入redux之后的store文件夹下面新建sagas:
import { takeEvery, put } from "redux-saga/effects";
// 触发saga的actionType
import { REDUX_SAGAS } from "./actionType";
// 请求完API之后的流程
import { reduxSuccess } from "./actionCreatores";
import axios from "axios";
function* mySaga() {
yield takeEvery(REDUX_SAGAS,t_sagas)
}
function* t_sagas() {
console.log('测试redux-saga!!!')
yield axios.get('http://ghhmzjd.tillage-cloud.com:8002/pangu/datacenter/dataCenter/intelligentScenic/crowd')
const action = reduxSuccess()
// 这里相当于store.dispatch(action)
yield put(action)
}
export default mySaga;
actionCreatores.js:
import {
REDUX_SAGAS,
REDUX_SAGAS_SUCC
} from "./actionType";
export const reduxSagas = (data) => ({
type: REDUX_SAGAS,
data
})
export const reduxSuccess = () => ({
type: REDUX_SAGAS_SUCC,
})
actionType.js:
// sagas
export const REDUX_SAGAS = 'reduxSagas'
export const REDUX_SAGAS_SUCC = 'reduxSagasSucc'
reducer.js
import {
REDUX_SAGAS,
REDUX_SAGAS_SUCC
} from "./actionType";
const defaultState = {
reduxSagas: "",
flag: "等待执行redux-saga"
}
export default (state = defaultState, action) => {
if (action.type === REDUX_SAGAS) {
let newState = JSON.parse(JSON.stringify(state))
newState.reduxSagas = action.data
return newState
}
if (action.type === REDUX_SAGAS_SUCC) {
let newState = JSON.parse(JSON.stringify(state))
newState.flag = 'success'
return newState
}
return state
}
sagas.js:
import { createStore , applyMiddleware ,compose } from "redux";
import reducer from "./reducer";
import createSagaMiddleware from "redux-saga";
// 引入saga的业务逻辑
import mySagas from "./sagas";
const sagaMiddleware = createSagaMiddleware();
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose;
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware))
const store = createStore(
reducer,
enhancer
)
sagaMiddleware.run(mySagas)
export default store
最后是我们的视图层 app.js:
import React, { Component, Fragment} from 'react';
import 'antd/dist/antd.css'
import { Button, Card, Statistic } from "antd";
// redux
import store from "./store";
// redux的枚举
import { statelessValue , reduxSagas} from "./store/actionCreatores";
class App extends Component {
constructor(props) {
super(props);
this.state = {
...store.getState()
}
this.storeChange = this.storeChange.bind(this)
store.subscribe(this.storeChange) // 订阅redux的状态
}
storeChange() {
this.setState(store.getState())
}
testReduxSagas () {
const action = reduxSagas()
store.dispatch(action)
}
render() {
return (
<Fragment>
<Button type="primary" onClick={this.testReduxSagas.bind(this)}>redux-sagas</Button>
<div>{this.state.flag}</div>
</Fragment>
);
}
}
export default App;
在视图上点击了按钮之后在saga中间件中发起请求,最后请求成功,更新flag,视图最后渲染新的flag。