redux使用combineReducers多次初始化reducer

最近在用react编写项目使用redux的时候发现,redux多次初始化reducer

具体代码如下

//reducer
function reducer1(state  = null,action) {
    console.log('reducer1',action)
    const {data,type} = action
    if (type === 'TEST1') {
        return  state
    }else {
        return  state
    }
}

const reducers = combineReducers({
    reducer1:reducer1
})

//store
const store = legacy_createStore(reducers)

经过测试发现 console.log('reducer1',action)打印三次也就是初始化的时候调用了三次reducer还有就是combineReducers()方法每多一个reducer就会增加三次输出。另一个有趣的现象如下代码

//reducer
function reducer1(state  = null,action) {
    console.log('reducer1',action)
    const {data,type} = action
    if (type === 'TEST1') {
        return  state
    }else {
        return  state
    }
}

//store
const store = legacy_createStore(reducer1)

console.log('reducer1',action)只会打印一次,也就是说除去legacy_createStore做的初始化实际combineReducers()函数会做两次初始化。至于为什么这样做有兴趣的可以看看源码

你可能感兴趣的:(react,react.js,redux,js)