之前说过一篇通过redux-thunk实现redux的异步调用,今天我们通过代码来看看这两个在实现上的区别.
redux-saga可以处理各种复杂的异步操作,redux-thunk适⽤于简单的异步操作场景
redux-saga使用generator解决异步问题,使⽤同步方式编写异步代码,解决回调地域问题
redux-thunk可以接受function类型的action,而redux-saga则 是纯对象action的解决⽅案
我们来修改上一篇中的路由守卫的代码,之前是使用redux-thunk实现的异步操作,今天采用redux-saga对他进行改造.在此之前大家需要先了解generator函数.
首先安装redux-saga
npm install redux-saga -S or
cnpm install redux-saga -S or
yarn add redux-saga
安装成功后启动项目开始改造我们的代码
我们在src/store下面创建一个新的saga.js文件来编写我们的saga代码.
src/store/login-redux.js
const initState = {
login: false,
loading: false,
errmsg: ""
}
export const loginReducer = (state=initState, action) => {
switch(action.type){
case "nowlogin":
return {
login: false,
loading: true,
errmsg: ""
}
case "haslogin":
return {
login: true,
loading: false,
errmsg: ""
}
case "loginfail":
return {
login: false,
loading: false,
errmsg: action.message
}
default :
return state
}
}
//这个文件没有太大的变化,新添加一个触发saga的action文件,并导出
function login (name){
return {type: "LOGIN_REQUEST", name}
}
export {login}
src/store/saga.js
//call用来调用异步方法,put派发reduer的action以及获取的值, takeEvery监听触发saga的事件
import { call, put, takeEvery } from "redux-saga/effects"
//模拟一个异步方法
const user = {
login(name){
return new Promise((reslove, reject) => {
setTimeout(()=>{
//当用户输入的值等于tom则登录成功,否则失败
if(name == "tom"){
reslove({name: "tom", age: 20})
}else{
reject("用户名或密码有误")
}
},1000)
})
}
}
//执行异步方法并派发action,因为这个过程可能会报错,用try,catch来捕获
function *login(action){
try{
yield put({type: "nowlogin"})
const res = yield call(user.login, action.name)
yield put({type: "haslogin", res})
}catch (message){
yield put({type: "loginfail", message})
}
}
//监听触发saga事件,并执行上面的generator login函数
function* mysaga(){
yield takeEvery("LOGIN_REQUEST",login)
}
export default mysaga
src/store/index.js
import { createStore, applyMiddleware, combineReducers } from "redux"
import logger from "redux-logger"
import {loginReducer} from "./login-redux"
import {countRedux} from "./count-redux"
import createSagaMiddleware from "redux-saga"
import saga from "./saga"
const mid = createSagaMiddleware();
const store = createStore(combineReducers({
count: countRedux,
login: loginReducer
}), applyMiddleware(logger, mid))
mid.run(saga)
export default store;
src/routerdemo.js
//其他代码和上一篇一样,我们在这只展示修改的地方
import React,{ useState } from "react"
import { BrowserRouter as Router, Route, Link, Redirect, Switch } from "react-router-dom"
import { connect } from "react-redux"
import {login} from "./store/login-redux"//引入触发saga的action
//修改登录组件
const Login = connect(state => (
{isLogin: state.login.login,
loading: state.login.loading,
error: state.login.errmsg}//加入了登录失败的错误信息
),{login})(
function ({location, isLogin, loading, login, error}){
const fromUrl = location.state&&location.state.jumpUrl || "/";
if(isLogin){
return <Redirect to={fromUrl}></Redirect>
}
const [name, setname] = useState("");
return(
<div>
//将用户输入的值存入状态中
<input type="text" onInput={(e) => setname(e.target.value)}/><br />
<button onClick={() => login(name)}>{loading? "登录中..." : "登陆"}</button>
{error && <p style={{color: "red"}}>{error}</p>}//如果失败,展示错误信息
</div>
)
}
)
查看页面