react redux异步方法总结

作者: MJ 分类: react 发布时间: 2019-04-22 10:53

redux异步的方法有很多,常用的也就那几种: redux-thunk,redux-actions,redux-promise,redux-saga ,dva

1:redux-thunk

https://github.com/reduxjs/redux-thunk

安装:yarn add redux-thunk

index.js

import thunk from 'redux-thunk';//处理异步action
import {createStore,applyMiddleware} from 'redux';
const store = createStore(rootReducer,applyMiddleware(thunk,promise,logger));

2:redux-actions

https://github.com/redux-utilities/redux-actions

3: redux-promise

4: redux-saga

https://redux-saga-in-chinese.js.org/

使用:

index.js

import createSagaMiddleware from 'redux-saga';//引入saga
import rootSaga from './sagas';//引入所有saga模块
sagaMiddleware.run(rootSaga);//run saga

sagas/index.js

import { all } from 'redux-saga/effects';
// import { helloSaga } from './counter';
// import { getUsers,getTodos } from './user';
// import * as helloSaga from './counter';
// import * as userSaga from './user';
// console.log(Object.values(userSaga));
import {userSagas} from './user';
import {hellos} from './counter';
// console.log([...userSagas]);
export default function* rootSaga(){
    // yield all([
    //     helloSaga()
    // ]);
    // yield all([
    //     ...Object.values(helloSaga),
    //     ...Object.values(userSaga)
    // ].map(fork));
    yield all([
        ...userSagas,
        ...hellos
    ])
}

sagas/counter.js

import { JIAASYNC } from  '../constants';
import { takeEvery,put } from 'redux-saga/effects';
const delay = (ms) => new Promise(resolve => setTimeout(resolve,ms));
function* jiaAsync(){
    yield delay(2000);
    yield put({type:'JIA'});
}
function* helloSaga(){
    yield takeEvery(JIAASYNC, jiaAsync);
}

export const hellos = [
    helloSaga()
]

sagas/user.js

import { takeEvery,call,put } from 'redux-saga/effects';
import axios from 'axios';

function* getUser(){
    try {
        const user = yield call(axios.get,'http://jsonplaceholder.typicode.com/users');
        yield put({type:'GET_USER_YES',user:user});
    } catch (error) {
        yield put({type:'GET_USER_NO',error:error.message});
    }
}
function* getTodo(){
    const todos = yield call(axios.get,'http://jsonplaceholder.typicode.com/todos');
    console.log(todos);
}
function* getUsers(){
    yield takeEvery('GET_USER',getUser)
}
function* getTodos(){
    yield takeEvery('GET_TODO',getTodo)
}

export const userSagas = [
    getUsers(),
    getTodos()
]

5: dva

https://dvajs.com/guide/

参考:https://segmentfault.com/a/1190000007248878

欢迎关注小程序,感谢您的支持!

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。 必填项已用*标注