简体   繁体   English

React Redux组合减速器

[英]React Redux Combine Reducers

In Redux, if I am using say a data structure as follows: 在Redux中,如果我使用的话说如下数据结构:

{ 
    products: [ 
                {id:1, name:'tv', description:'A color Sony TV', cost:1000}, 
                {id:2, name:'remote control', description:'A black compact Remote Control', cost: 999}
    ],
    shoppingCart: [],
    checkoutCart: []
}

And I use the Redux combineReducers 我使用Redux combineReducers

combineReducers({products, shoppingCart, checkoutCart})

If I wanted to copy the shopping Cart data into the checkoutCart say on a click event, where would I do so / or should I do so ? 如果我想将shopping Cart数据复制到checkoutCart说明点击事件,我会在哪里这样做/或者我应该这样做?

When you use combineReducers you're assuming the reducers are indepedent and they cannot see each other's state. 当你使用combineReducers你假设减速器是独立的,他们无法看到彼此的状态。 Each reducer will only receive a "slice" of the state. 每个reducer只会收到一个州的“切片”。

In order to achieve what you want, I would consider joining the shoppingCart and checkoutCart reducers / state into a single one and using switch (action.type) to know what to do. 为了达到你想要的效果,我会考虑将shoppingCartcheckoutCart reducers / state加入一个并使用switch (action.type)来知道该怎么做。

Now you can simply create an action on your new reducer that returns something like 现在,您只需在新的reducer上创建一个返回类似的操作

{ checkoutCart: clone(state.shoppingCart) } {checkoutCart:clone(state.shoppingCart)}

I would use an action and send the whole shopping cart data as payload 我会使用一个动作并将整个购物车数据作为有效载荷发送

If it is difficult to pass the data of the shopping cart in the component you could access the state in the action creator as described here https://stackoverflow.com/a/35674575/1868008 but you need to use redux-thunk 如果很难传递组件中购物车的数据,您可以访问动作创建器中的状态,如https://stackoverflow.com/a/35674575/1868008所述,但您需要使用redux-thunk

If you want to clone your shoppingCart to the checkoutCart . 如果您想将shoppingCart克隆到checkoutCart You could in your onClick function pass this.props.shoppingCart as a parameter to your action call. 您可以在onClick函数this.props.shoppingCart作为参数传递给您的动作调用。

onClick(e) {
    this.props.checkOutActions.checkOut(this.props.shoppingCart);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM