redux-saga
安装
yarn add redux react-redux redux-saga -S
使用
- redux/store.js
// 导入applyMiddleware中间件
import {createStore,applyMiddleware} from 'redux';
// 导入createSagaMidldleware中间件
import {createSagaMiddleware} from 'redux-saga';
// 导入reducers
import reducers from './redux/reducers';
// 导入rootSaga异步处理方法
import rootSaga from './redux/saga';
// 创建sagaMiddleware实例对象
const sagaMiddleware=createSagaMiddleware();
// 创建store对象
const store=createStore(reducers,applyMiddleware(sagaMiddleware));
// 运行saga
sagaMiddleware.run(rootSaga);
// 导出store对象
export default store;
- redux/saga.js
// 导入saga提供的方法
import {put,call,all,takeEvery,delay} from 'saga/effects';
// root saga: 启动所有的saga监视器
function* rootSaga(){
yield all([watcherSaga()])
}
// watcher saga: saga监视器
function* watcherSaga(){
yield takeEvery('get_data_async',getMessage);
}
// worker saga: 真正发请求的saga
function* getMessage(){
// 延时2s
yield delay(1000);
// 发送异步请求
const response=yield call(fetch,'http://106.13.182.88:8081/get.php');
// 将response对象转换成json对象
const data=yield response.json();
// 通过put触发对应的action
yield put({type:'get_data',data});
}
- redux/reducers.js
// 合并reducers
import {combineReducers} from 'redux';
const initData=[];
function message(state=initData,action){
switch(action.type){
case 'get_data':
return action.data;
break;
default:
return state;
}
}
// 合并并导出reducers
export default combineReducers({message});
- redux/actions.js
// 同步action
export const get_data=(data)=>({type:'get_data',data});
// 异步action
export const get_data_async=()=>({type:'get_data_async'})
- 根组件: App.jsx
import {connect} from 'react-redux';
//导入action
import {get_data_async} from './redux/actions'
export default class App extends React.Component{
request(){
// 触发异步aciton; 从而触发takeEvery('get_data_async',getMessage)的执行
this.props.get_data_async();
}
render(){
return (
<div>
<button onClick={()=>{this.request()}}>request</button>
</div>
)
}
}
export default connect({
(state)=>(}{message:state.message}),
{get_data_async}
})(App)
- 入口文件:index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
// 导入根组件
import App from './App';
ReactDOM.render(<Provider store={store}><App/></Provider>,document.querySelector('#root'));