# redux-saga-message **Repository Path**: duans/redux-saga-message ## Basic Information - **Project Name**: redux-saga-message - **Description**: 使用redux-saga实现异步action的留言板案例 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-01-13 - **Last Updated**: 2022-06-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # redux-saga ## 安装 `yarn add redux react-redux redux-saga -S` ## 使用 - redux/store.js ```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 ```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 ```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 ```js // 同步action export const get_data=(data)=>({type:'get_data',data}); // 异步action export const get_data_async=()=>({type:'get_data_async'}) ``` - 根组件: App.jsx ```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 (