2016-08-12 81 views
0

鉴于one of react-redux's official hello world example,如何实现multiply减速器?他们实现了一个增加两个数字的减速器,但是看到一个输入作为乘数的减速器也是有益的。我知道这是非常基本的,但它是我另一个项目的分解版本。向最简单的Redux添加乘法减速器示例

这里是我在使这项工作的尝试:

const MULTIPLY_ACTION = 'MULTIPLY_ACTION' 
    function multiplyAction(integer) { 
    return { 
     type: MULTIPLY_ACTION, 
     integer 
    } 
    } 

export function multiplier(state = { integer: 0 }, action) { 
    switch() { 
    case MULTIPLY_ACTION: 
     console.log('multiplying', action) 
     return { 
     multiple: state.integer * action.multiplier 
     } 
    default: 
     return state 
    } 
} 

问题我遇到:

  1. 重构,使mapStateToProps()与多个减速工作。我错过了什么? [请参阅下面的重构]
  2. increaseAction对象文字重构为函数(动作类型?)。在原始示例中,当我将const increaseAction = { type: 'increase' }重构为const increaseAction =() => {type: 'increase'}时,计数器缩减器不再被调用,并且我的应用程序默默失败(我正在使用create-react-app作为构建版本)。

[重构]。

function mapStateToProps(state) { 
    const { increaseAction, multiplyAction } = state 

    return { 
    increaseAction, 
    multiplyAction 
    } 
} 

非常感谢!

回答

1

首先,你的动作作为一个对象被分派给你的reducer,所以你需要使用你定义的对象形状。例如,您将您的操作定义为具有一个类型:MULTIPLY_ACTION,以及(通过使用属性简写语法)一个名为integer的属性,将其设置为integer参数的值。

因此,您的reducer需要根据类型进行切换(您现在在switch语句中有一个空的表达式,而不是说action.type),然后它需要使用action.integer

然后,你的reducer代表你的总应用程序状态对象的一部分。现在您将该状态的默认形状定义为integer属性的值为0的对象。您会希望动作case语句返回与默认状态对象相同的形状,所以它应该返回对象具有称为integer的单个属性。换句话说,你的reducer应该总是返回相同的对象形状(即使属性不同也可能为null,如果这对你的应用程序来说是一个有效值)。上面写着:

return { integer: state.integer * action.integer } 

至于你的连接功能,mapStateToProps只知道你的状态(不是你的行动),因此它只是需要返回所需状态的一部分。它是第二个参数,mapDispatchToProps,与您的操作有关。所以,你想要的东西,如:

connect(
    state => ({ 
    multiplierInteger: state.multiplier.integer // remember that you are looking within your reducer multiplier which contains an object that has the field you want, integer 
    }), 
    dispatch => ({ 
    multiplyAction(val) { 
     dispatch(multiplyAction(val)) 
    } 
    }) 
) 

编辑:这可能是我误会了你的“重构”,现在看到你问有关使用mapStateToProps访问多个减速。那么我仍然认为我的例子可能会有所帮助,因为你试图通过相关行为的名称来访问reducer的结果。你想要的是使用reducer本身的名称,假设你使用combineReducers,它是Redux如何将许多reducer映射到单个状态对象。