2016-10-17 50 views
0

我有一种情况,我想将我的减速器拆分为多个文件,以便我可以正确管理。结合多个减速器

可以说我会用减速器做2件事。

  1. 只处理产品。
  2. 只处理联系人。

我可以在同一个文件中工作,但变得很难管理。

因此,我想拆分移动用户的可读性。

在这里,我试图分裂减速器的文件。

这是我将用于获取产品的减速器之一。

module.exports.products=function(state, action) { 
console.log("################################## branch_order"); 
console.log("reducer",state,action); 
if (state==null) { 
    return {}; 
} 
var new_state=$.extend(true,{},state); // XXX: deep-copy 
console.log(action.type,"action type") 
switch (action.type) { 
    case "PRODUCT_LOADING": 
     new_state.product_loading=true; 
     break; 
    case "PRODUCT_LOADED": 
     new_state.product_loading=false; 
     new_state.product=action.product; 
     break; 

} 
console.log("new_state",new_state); 
return new_state; 
} 

这里是另一个将存储联系人的减速器。

module.exports.contacts=function(state, action) { 
console.log("################################## pawn_order",state); 
console.log("reducer",state,action); 
if (state==null) { 
    return {}; 
} 
return state; 

}

这是怎么了我正在结合减速。

var product = require("./prodcut") 
var contact = require ("./contact") 
var combineReducers = require ('redux').combineReducers 


module.exports = combineReducers({product,contact}); 

这就是我在我的主文件中调用并将其传递给存储。

var reducers = require ("./reducer") /// <<<<< this is how i call 
var RPC = require('./RPC') 
//var actions = require("./actions") 
var createStoreWithMiddleware=applyMiddleware(thunkMiddleware)(createStore); 
var store=createStoreWithMiddleware(reducers); 
ReactDOM.render(<Provider store={store}><Index/></Provider> , document.getElementById('content')) 

我试图按照combine reducers的教程,但遇到了一些问题。

这种组合似乎工作。

出了什么问题?

当第一减速器被称为(产品),它的工作原理 当第二减速器被称为(接触)整个状态似乎被替换

我想将数据追加的状态(我不知道如何做到这一点请大家帮忙)

只是为了信息,这是我怎么骂我接触的状态数据:

var select=function(state){ 
return { 
    product_loading:state.product_loading, 
    product:state.product, 

} 
} 

这就是我如何拨打我的组件

render:function(){ 
    if (!this.props.product_loading) return <div> Loading</div> 

在此先感谢。期待一些解决方案。

+0

你可能会在一起工作的例子,所以我们可以玩它吗? (例如在jsbin上) –

+0

因此,reducer正在分离的状态树上工作,这意味着每个reducer都有自己的位和整个状态的bob。 因此,您不会看到“全局”状态(如从另一个减速器中看到的那样),但是您必须复制您当前减速器中感兴趣的状态。 –

回答

1

当使用combineReducers时,每个减速器只会看到一个状态片。

function r1(state) { 
    console.log (state); //logs v1 
} 

function r2(state) { 
    console.log (state); //logs v2 
} 

const c = combineReducers({ r1, r2 }); 

c({ r1: 'v1', r2: 'v2' }, { type: 'MY_ACTION' });