redux-saga实践与思考

redux-saga

对于redux-saga,网上的文章已经数不胜数,在这里重提redux-saga,主要是想记录一下最近使用redux-saga的一些考虑和看法,本文不会去讲解各个 Effect ,如有需要可查看文档

在redux-saga官网中的解释是一个saga就像是应用程序中一个单独的线程,独自负责处理副作用。第一次读完这句话,心里并没有太多的思考。因此后续在项目中也爬了许多坑。在这里我们需要明确两点,saga如何像一个单独的线程,在项目中具体是什么样的?什么叫做副作用?

首先来看两段示例代码:
代码一:

``` js
// getInitialData获取初始化数据 handleFetchShopData 获取商品数据
function* initialAct() {
    try {
        const res = yield call(getInitialData)
        const { code, userType } = res
        if(code === '0'){
            if(userType) {
                yield fork(handleFetchShopData, userType)
            }
        }
    } catch(err) {
        console.log('initialAct', err)
    }
}
function* handleFetchShopData(param) {
    // do something
}
export default {
    saga: function*() {
        yield fork(initialAct)
    }
}

```

代码二:

``` js
// action.js中定义INITIAL_COMPLETE
function initialActComplete(
    state = false,
    { type, payload } = {}
) {
    switch (type) {
        case INITIAL_COMPLETE:
            return payload
        default:
            return state
    }
}
function* initialAct() {
    try {
        const res = yield call(getInitialData)
        const { code, userType } = res
        if(code === '0'){
            if(userType) {
                yield put({
                    type: INITIAL_COMPLETE,
                    payload: userType
                })
            }
        }
    } catch(err) {
        console.log('initialAct', err)
    }
}
function* handleFetchShopData(param) {
    while (true) {
        let { payload } = yield take(INITIAL_COMPLETE);
        // do something
    }
}
export default {
    reducer: {
        initialActComplete
    },
    saga: function*() {
        yield fork(initialAct)
        yield fork(handleFetchShopData)
    }
}

```

持续输出ing.........

猜你喜欢

转载自www.cnblogs.com/MarphyDemon/p/11531151.html