sagas.js 中的代码
// redux-saga import { call, put,takeEvery } from 'redux-saga/effects' const Api ={ login(){} } // generator 生成器函数 function* login(){ try { const result = yield call(Api.login); yield put({type: 'login', result}) } catch(err) { yield put({type: 'login_failure', message: err.message) } } function* mySaga(){ yield takeEvery('login_request', login); } export default mySaga;
应用
import createSagaMiddleware from 'redux-saga' import saga from './sagas' // 1.创建中间件 const mid = createSagaMiddleware(); // 2.应用中间件 const store = createStore( // reducer模块化,合并 combineReducers({ counter, user }), applyMiddlerware(logger, mid) ) mid.run(saga); export default store;
user.redux.js
export function login (){ return {type: 'login_request'} }
login.js
import { login } from './redux/user.redux.js import { connect } from 'react-redux' @connect( state => state, { login } ) export default Login extends Component{ render(){ return( <div> <button onClick={ () => this.props.login }>登录</button> </div> ) } }