redux-thunk redux中间件
redux中间件,处理异步请求
actionCreators可以返回一个函数,在该函数里有参数dispatch,发送异步,异步成功之后分发action更改数据。
安装:
yarn add redux-thunk
配置:
1.从redux中引入applyMiddleware
import {applyMiddleware} from ‘redux’;
2.引入redux-thunk
import thunk from ‘redux-thunk’;
3.使用中间件,如果要使用Redux DevTools调试插件,引入增强函数
在store=>index.js中操作
import { createStore, applyMiddleware, compose } from ‘redux’;
import thunk from ‘redux-thunk’;
import reducer from ‘./reducer’;
const composeEnhancers = window.REDUX_DEVTOOLS_EXTENSION_COMPOSE ?
window.REDUX_DEVTOOLS_EXTENSION_COMPOSE({}) : compose;
const enhancer = composeEnhancers(applyMiddleware(thunk))
export default createStore(
reducer,
enhancer
//applyMiddleware(thunk)
);
4.使用redux-thunk生成action
可以返回一个函数,该方法有参数dispatch
可以在该函数内部进行异步处理,异步处理成功之后再分发action.
// redux-thunk的action
export const getToDoList = () => {
return (dispatch) => {
axios.get(‘https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList’).then((res) => {
//同步action
dispatch(getListAction(res.data.data.list));
});
}
}
1、新建项目
2、src目录下创建store文件夹,pages文件夹
pages文件夹下创建Article.jsx文件
store文件夹下创建reducers文件夹、actionCreators文件夹
actionCreators之下创建articleAction.js
reducers之下创建articleReducer.js、index.js
store文件夹下新建index.js文件,actionTypes.js
//Article.jsx文件
import react,{Component} from './react';
import {connect} from 'react-redux'
import {changeMsg,getDataAxAction} from '../store/actionCreators/articleAction';
class Article extends Component{
render(){
return (
<div>
hello
{JSON.stringify(this.props)}
<button onClick={this.props.changeMsg}>更改msg-同步</button>
<button onClick={this.props.getData}>获取数据-异步</button>
</div>
)
}
}
const mapStateToProps = (state,ownProps) =>{
return state;
}
const mapDispatchToProps = (dispatch,ownProps)=>{
return {
changeMsg:()=>{
//分发
dispatch(changeMsg('更改后的数据'))
},
getData:()=>{
//分发action,一个可以获取后台数据的action
dispatch(getDataAxAction({
page:0,
pageSize:10
}))
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Article);
//articleAction.js
import {CHANGE_MSG,CHANGE_ARTICLE} form '../actionTypes.js'
import axios from 'axios'
export const changeMsg = (value)=>{
return {
type:CHANGE_MSG,
value
}
}
//redux-thunk actionCreator
export const getDataAxAction = (value)=>{
//加了中间件之后可以返回一个函数
return (dispatch)=>{
axios.get('http://134/manager/article/findArticle',{params:value}).then((res)=>{
//分发一个action,由分发的action去更改数据
dispatch(changeArticles(res.data.list));
}).catch((error)=>{
console.log(error);
});
}
}
//更改store中的articles的
const changeArticles = (value)=>{
return {
type:CHANGE_ARTICLE,
value
}
}
//actionTypes.js
export const CHANGE_MSG = 'CHANGE_MSG';
export const CHANGE_ARTICLE = 'CHANGE_ARTICLE';
//articleReducer.js
import {CHANGE_MSG,CHANGE_ARTICLE} from '../actionTypes.js'
let initState = {
msg:'article',
articles:[]
};
export default (state=initState,action)=>{
if(action.type === CHANGE_MSG){
return {
...state,
msg:action.value
}
}
if(action.type === CHANGE_ARTICLE){
return {
...state,
articles:action.value
}
}
return state;
}
//reducer的index.js
import {combineReducers} from 'redux';
import article from './articleReducer'
export default combineReducers({
//命名空间
acticle:article;
});
//store的index.js创建store
//applyMiddleware redux使用中间件的方法
//compose增强函数,给devtools使用的函数
import {creactStore,applyMiddleware,compose} from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers';
//devtools与redux-hunk同时使用
//const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
//const enhancer = composeEnhancers(applyMiddleware(thunk))
//let store = creactStore(reducer,enhancer);
let store = creactStore(reducer,appltMiddleware(thunk));
export default store;
redux-saga ['sɑɡə] redux中间件
使用generator函数在sagas文件中共处理业务逻辑,有了redux-saga之后,除了reducer可以接收action,sagas也可以接收并做业务逻辑处理
安装
yarn add redux-saga
配置
1.使用中间件,如果要使用Redux DevTools调试插件,引入增强函数compose
import { createStore, applyMiddleware, compose } from ‘redux’;
import createSagaMiddleware from ‘redux-saga’;
const composeEnhancers = window.REDUX_DEVTOOLS_EXTENSION_COMPOSE ? window.REDUX_DEVTOOLS_EXTENSION_COMPOSE({}) : compose;
const sagaMiddleware = createSagaMiddleware();
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware))
// 注入reducer,和中间件
export default createStore(
reducer,
enhancer
);
2.创建sagas.js配置文件并引入到store中
redux-saga把业务逻辑单独写一个文件
sagas.js
function* mySaga() {}
export default mySaga;
index.js
import mySagas from ‘./sagas’;
sagaMiddleware.run(mySagas); //执行run方法,运行saga。注意运行的时机是在store创建好了之后,将中间件挂上去之后。
3.使用
组件挂载完毕之后,声明actionType,声明actionCreators,在组件中分发action,在sagas.js中处理业务逻辑
import { takeEvery, put } from ‘redux-saga/effects’;
function* mySaga() {
// 写业务逻辑
yield takeEvery(GET_MY_LIST, getList)
}
function* getList() {
// 可以写业务逻辑
const res = yield axios.get(‘https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList’);
yield put(getListAction(res.data.data.list));
/* axios.get(‘https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList’).then((res) => {
// dispatch(getListAction(res.data.data.list));
// saga带的put方法
put(getListAction(res.data.data.list));
}); */
}
export default mySaga;
ES6 generator函数 暂缓执行,可以分段使用
//generator.js
function* test(){
console.log(1);
yield 1;
console.log(2);
yield 2;
console.log(3);
yield 3;
console.log(4);
return 4;
}
let temp = test();//暂缓执行,只有.next方法才会执行
console.log(temp);//Object [Generator] {}
console.log(temp.next());//{value:1,done:false}
1、新建项目
2、src目录下创建store文件夹,pages文件夹
pages文件夹下创建Article.jsx文件
store文件夹下创建reducers文件夹、actionCreators文件夹、mySagas.js文件(处理业务逻辑)
actionCreators之下创建articleAction.js
reducers之下创建articleReducer.js、index.js
store文件夹下新建index.js文件,actionTypes.js
//store之下的index.js
// 创建store
import { createStore, applyMiddleware, compose } from 'redux';
import reducer from './reducers';
import createSagaMiddleware from 'redux-saga';
import mySagas from './mySagas';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
// 创建saga中间件
const sagaMiddleware = createSagaMiddleware();
//使用中间件
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware))
let store = createStore(
reducer,
enhancer
);
// 在这里使用mySagas
sagaMiddleware.run(mySagas);
export default store;
//mySagas.js
//处理业务逻辑的,如果发送了action,这里可以监听,然后处理异步
//put用来转发action
import axions from 'axios';
import {takeEvery,put} from 'redux-saga/effects'
import {GET_DATA_SA_ACTION,DELETE_DATA_SA_ACTION} from '../actionTypes'
import {changeArticles,getDataSaAction} from './actionCreators/articleAction'
function* mySagas(){
console.log(1111);
//takeEvery监听某个action,然后执行第二个参数的generator函数
tield takeEvery(GET_DATA_SA_ACTION,getList);
}
//action就是对应的action对象
fuction* getList(action){
//发送异步,异步成功之后分发action
let res = tield axios.get('http://134/manager/article/findArticle',{params:action.value});
//put就是转发action,类似于dispatch
yield put(changeArticles(res.data.list));
}
function* deleteData(action) {
// 发送异步,异步成功之后,分发action
let res = yield axios.get('http://134.175.154.93:8099/manager/article/deleteArticleById', { params: action.value });
// put就是转发anction,类似于dispatch
yield put(getDataSaAction({ page: 0, pageSize: 10 }));
}
export default mySagas;
//articleAction.js
//redux-saga的action
export const getDataSaAction = (value)=>{
return {
type:GET_DATA_SA_ACTION,
value
}
}
//删除数据
export const deleteDataById = (value)=>{
return {
type:DELETE_DATA_BY_ID,
value
}
}
//article.jsx
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { changeMsg, getDataAxAction, getDataSaAction, deleteDataSaAction } from '../store/actionCreators/articleAction';
class Article extends Component {
render() {
return (
<div>
hello
{JSON.stringify(this.props)}
<button onClick={this.props.changeMsg}>更改msg-同步</button>
<button onClick={this.props.getData}>异步获取数据</button>
<button onClick={this.props.deleteDataById}>异步删除数据</button>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return state;
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
changeMsg: () => {
// 分发
dispatch(changeMsg('更改后的数据'));
},
getData: () => {
// 分发action
dispatch(getDataSaAction({ page: 0, pageSize: 10 }));
},
deleteDataById: () => {
// 分发action
dispatch(deleteDataSaAction({ id: 3984 }));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Article);