redux-saga简单使用

github上
API

拦截actions,异步处理,转发reducer,在action与reducer之间

1:初始化项目

create-react-app
yarn add redux react-redux

构建基本的react redux react-redux项目

2安装redux-saga

yarn add redux-saga

使用

为了能跑起 Saga,我们需要使用 redux-saga 中间件将 Saga 与 Redux Store 建立连接。

import createSagaMiddleware from 'redux-saga'
const sagaMiddleware = createSagaMiddleware()
applyMiddleware(sagaMiddleware)

sagaMiddleware.run(mySaga)

进程化

es6的generator

function* gen(){
  console.log("888")
}
gen();//无输出
console.log(gen())//输出[object Generator] { ... }
gen().next()//执行了console.log("888")

next():执行生成器内全部的代码,

yield关键字

function* gen(){
  yield console.log("888");
  yield console.log("666");
  yield console.log("777");
}

gen().next()
gen().next()
gen().next()

输出:
“888”
“888”
“888”
只执行了第一行的输出语句

 function* gen(){
  yield console.log("888");
  yield console.log("666");
  yield console.log("777");
  console.log("all done")
}
	var mygen = gen()
	mygen.next()
	mygen.next()

输出:
“888”
“666”
定义成变量后,能执行里面的语句,像进程一样可以停止

next传参

function* gen(){
  yield console.log("888");
  yield console.log("666");
  yield console.log("777");
}

var mygen = gen()
console.log(mygen.next())

输出:“888”
[object Object] {
done: false,
value: undefined
}
输出了一个对象:done:是否执行完,value:yield后的东西

function* gen(){
  var name = yield console.log("888");
  yield console.log(name + "666");
  yield console.log("777");
}

var mygen = gen()
console.log(mygen.next())
mygen.next("ruby")

输出:“888”
[object Object] {
done: false,
value: undefined
}
“ruby666”
name为yield 的返回值,即是输出的value值,下一个next传的参,会当成上一个next的返回值,name成了下一个next中的参数值

作用:

同步语句写异步代码

自动执行next()方法

一次完整的saga异步操作、

src>index

	import createSagaMiddleware from 'redux-saga'
    const sagaMiddleware = createSagaMiddleware()
	applyMiddleware(sagaMiddleware)
	
	sagaMiddleware.run(mySaga)//这样做只能执行一个saga

src/App.js

import { get_user } from './actions/user';

src/actions/user.js:单纯的action,异步操作交给saga

export const get_user = () => {
  return {
    type: 'FETCH_USER_REQUEST'
  }
};

src/sagas/index.js

import { delay } from 'redux-saga';
import { takeEvery, put, call, all } from 'redux-saga/effects';

export function* fetchUser() {
  const user = yield call(axios.get, "https://jsonplaceholder.typicode.com/users");//call()更好的执行异步操作
  console.log(user);//如果需要重发一个action
}

export function* watchFetchUser() {
  yield takeEvery('FETCH_USER_REQUEST', fetchUser);//拦截第一个参数:action发送的type,执行第二个参数方法
}

缺点:saga不能执行多个

执行多个sage

all方法

yield[]里的能并发执行,但是yield过期了,使用all

export default function* rootSage() {
  yield all([//这里的并发执行,那么
    watchIncrementAsync(),
    watchFetchUser()
  ]);
}
sagaMiddleware.run(rootSage)//这样就能并发执行watchIncrementAsync,watchFetchUser;

这样的话,没有实现saga的模块化

一些API的用法

import { takeEvery,call,put,delay  } from 'redux-saga/effects'l

yield takeEvery(‘INCREMENT_ANSY’, fetchUser);第一个参数拦截的action type,第二个参数,要执行的动作
call包裹异步操作能更好的处理
delay:延时器yield delay(3000);
put:发送其他action:yield put({ type:INCREMENT })

你可能感兴趣的:(redux-saga)