react系列学习(二)——react-saga使用方法
1,上一篇记录了redux,redux是同步的,既发出action指令后,reducer立即计算store,并返回。那么异步问题该如何解决?从后台请求获取的数据如何存储到store?这就是中间件的作用,也就是redux-saga的用处。2,index文件同样是合并多个saga,便于管理代码,和reducer的合并一样import {all} from 'redux-saga/effects';im
1,上一篇记录了redux,redux是同步的,既发出action指令后,reducer立即计算store,并返回。那么异步问题该如何解决?从后台请求获取的数据如何存储到store?这就是中间件的作用,也就是redux-saga的用处。
2,index文件同样是合并多个saga,便于管理代码,和reducer的合并一样
import {all} from 'redux-saga/effects';
import helloSaga from './helloSage';
import watchIncrementAsync from './incrementAsyncSaga'
export default function* rootSaga() {
yield all([
helloSaga(),
watchIncrementAsync()
]);
}
3,下面以incrementAsyncSaga.js为例(功能为从后台请求用户名,显示在页面上。)
saga可以视为是一个reducer,能够处理异步的reducer。所以saga同样是接收action指令,执行相应操作,只不过saga不进行计算,而是发送新的指令到reducer,让reducer来计算新的store。
import { put, takeEvery, all, call } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import { addTodo, showData } from '../creatAction';
import * as ct from '../creatAction/action';
function getData() {
return fetch("/api/test/profile",{
method:"GET",
credentials: 'include'
}).then((response)=>{
console.log(response);
return response.json()
}).then((response)=>{
console.log(response)
return response;
}).catch((error)=>{
console.log(error)
})
}
// Our worker Saga: 将执行异步的 increment 任务
function* incrementAsync() {
const resData = yield call(getData);
console.log(resData.user)
yield put(showData(resData.user));
// yield put(addTodo(1))
}
// Our watcher Saga: 在每个 INCREMENT_ASYNC action spawn 一个新的 incrementAsync 任务
export default function* watchIncrementAsync() {
yield takeEvery(ct.ASYNC_TODO, incrementAsync)
}
tackEvery,第一个参数为action,第二个参数为要执行的方法。当action匹配时,便执行incrementAsync;
incrementAsync方法中,首先通过fetch向后台请求数据,请求结束后,返回请求结果,第二步,yield put(showData(resData.user));发送action,改变store。put相当于store.dispatch。
4,使用方法
<h1>{store.getState().showUser}</h1>
<button onClick={() => store.dispatch(asyncTodo())}>异步</button>
action
// 异步
export const ASYNC_TODO = 'INCREMENT_ASYNC';
// 显示user
export const ASYNC_USER = 'SHOWUSER_ASYNC';
creatAction
import * as ct from './action';
//异步
export function asyncTodo(text) {
return {
type: ct.ASYNC_TODO,
text
}
}
//显示用户名
export function showData(text) {
return {
type: ct.ASYNC_USER,
text
}
}
reducer
import * as ct from '../creatAction/action';
const showUserRducer = (state='haha', action) => {
switch (action.type) {
case ct.ASYNC_USER: return action.text;
default: return state;
}
};
export default showUserRducer;
5,总结
redux-saga做的事情是,首先发送请求,请求成功后,在向reducer发送指令,重新计算store。
主要应用es6的Generator函数
function* incrementAsync() {
const resData = yield call(getData);
yield put(showData(resData.user));
}
更多推荐
所有评论(0)