redux-saga Practice and Reflection

redux-saga

For redux-saga, online articles have been numerous, here revisit redux-saga, I mainly want to record some of the considerations and opinions about the most recently used redux-saga, this article will not go to explain each Effect, if necessary, to view the document .

Redux-saga explained in the official website is a saga like the application a separate thread, solely responsible for side effects. The first reading of this sentence, did not mind too much thinking. So follow the project also climbed many pit. Here we need to clear two points, how saga as a separate thread, the project specifically what kind of? What is the side effects?

First, look at two sample code:
Code a:

``` 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)
    }
}

```

Code II:

``` 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)
    }
}

```

Continuous output ing .........

Guess you like

Origin www.cnblogs.com/MarphyDemon/p/11531151.html