是个什么东西呢?redux-saga 是 redux 一个中间件,用于解决异步问题。具体可以去百度搜索一下。不在这里过多介绍了
如何使用redux-saga?
先看下我的结构,分为了四个文件夹
acions> 表示动作 constants>一些变量的定义 reducers>也是表示动作 sagas>中间件处理
下面来实现异步请求Api的功能
创建constants/index.js
export const FETCH_REQUESTT = 'FETCH_REQUESTT'
创建acions/test.js
import { FETCH_REQUESTT} from './constants/index'
export const fetchuserr = () => {
return {
type: FETCH_REQUESTT
}
创建reducers/index.js
import { combineReducers } from 'redux'
import uss from './test'
export default combineReducers({
uss
})
这里使用了redux的combineReducers 具体是什么可点击链接友情链接
再创建reducers/test.js
const initialState = {
isFetch: false,
error: null,
user: null
}
const u = (state = initialState, action = {}) => {
switch (action.type) {
case 'FETCH_REQUESTT':
return {
isFetch: true,
error: null,
user: null
}
case 'FETCH_SUCESS':
return {
isFetch: false,
error: null,
user: action.uu
}
case 'FETCH_FAIL':
return {
isFetch: false,
error: action.errors,
user: null
}
default :
return state
}
}
export default u
创建sagas/index.js
import { all } from 'redux-saga/effects'
import rootUserr from './test'
export default function * rootSaga () {
yield all([ // 同时并发多个
...rootUserr,
])
}
再创建sagas/test.js
import { call, takeEvery, put } from 'redux-saga/effects'
import axios from 'axios'
function * fetchuserr () {
try {
const users = yield call(axios.get, 'https://jsonplaceholder.typicode.com/todos')
console.log('users' + users)
yield put({ type: 'FETCH_SUCESS', uu: users })
} catch (e) {
yield put({ type: 'FETCH_FAIL', errors: e })
}
}
function * userr () {
yield takeEvery('FETCH_REQUESTT', fetchuserr) // 正在加载数据
}
// 使用数组导出
const rootUserr = [
userr()
]
export default rootUserr
不了解put、takeEvery、call的可以百度一下
以上基本的业务逻辑已经处理好了
我们需要在入口文件index.js去包起来
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
//中间件
import {Provider} from 'react-redux' // 1,引用Provider
import {createStore,applyMiddleware} from 'redux' //2,引用中间件
import createSagaMiddleware from 'redux-saga' //3,引入createSagaMiddleware
import rootSaga from './pages/reduxsagas/sagas/index'; // 4,自己写的根 rootSaga
import rootReducer from './pages/reduxsagas/reducers/index'; //5,引入 reducers
const sagaMiddleware = createSagaMiddleware() // 6, 创建中间件
const store = createStore(
rootReducer,
applyMiddleware(sagaMiddleware)
)
)
// 4:启动 saga
sagaMiddleware.run(rootSaga);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
引入完成接下来就可以再页面中去使用了
pages/text.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Button, Card } from 'antd'
import { fetchuserr } from './../reduxsagas/actions/counter'
class saga extends Component {
render () {
return (
<div>
<Button type='primary' onClick={() => this.props.fetchuserr()}>测试请求</Button>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
// state 对应的 key, 在 reducers/index.js 中声明。
userta: state.uss
}
}
export default connect(mapStateToProps, { fetchuserr })(saga)
大功告成!
GitHub有更详细的介绍 链接