我可以在mapStateToProps

时间:2018-01-03 01:53:51

标签: reactjs react-redux

我正在学习React和Redux并发现以下问题,我无法理解,我在商店中有一个配置对象,可能看起来像这样:

{
    general:{duration:100,strength:100},
    gameA:{strength:50},
    gameB:{duration:50}
}

一般对象将始终存在并且将具有所有属性,并且它可以具有一个或多个具有全部或部分覆盖属性的游戏对象。

现在,游戏GameAGameB正在使用durationstrength道具,所以我可以这样做:

const mapStateToProps = (state) => {
    return {
        duration: state.general.duration,
        strength: state.general.strength
}
export default connect(mapStateToProps)(GameA);

但正如我的商店示例所示,我可以为每种游戏类型设置不同的设置,然后覆盖常规设置。我可以在mapStateToProps函数中执行此操作吗?

const mapStateToProps = (state) => {
    let {duration, strength} = state.general;
    if(state.gameA && state.gameA.duration) duration = state.gameA.duration;
    if(state.gameA && state.gameA.strength) strength= state.gameA.strength;
    return {
        duration: duration,
        strength: strength
}

1 个答案:

答案 0 :(得分:3)

另一种模式是使用reselect来计算来自state的派生值:

https://redux.js.org/docs/recipes/ComputingDerivedData.html#composing-selectors

选择器提供了记忆派生值的好处,考虑到反应生命周期方法的敏感性,这证明非常有用(如果你不必这么做,为什么要多次计算?)。

我发现它们对于从组件中抽象表示逻辑非常有用。

这是一个简短而简单的例子:

const mapStateToProps = state => ({
  price: getPriceWithDollarSign(state), 
})

// selectors/price.js
const getProduct = (state) => state.product // returns { price: 7.00 }

// i find it useful to immediately identify selectors with `get` so I know its a selector
export const getPriceWithDollarSign = createSelector(getProduct, (item) => {
  // this will only be evaluated once for this specific item, future calls to this method
  // will return the value cached by re-select (until the methods input changes)
  return `$${item.price}` // item is value returned by getProduct
})

在您的组件中,您最终会得到this.props.price -> '$7.00'

reselect的美妙之处在于它能够组合多个选择器,从而可以轻松地共享和使用其他选择器。

查看https://github.com/reactjs/reselect了解详情。

虽然重新选择的使用是为了从redux状态派生值,但您可以将该库与任何数据结构/库/框架一起使用。

相关问题