gpt4 book ai didi

reactjs - 我可以操作 mapStateToProps 中的值吗

转载 作者:行者123 更新时间:2023-12-03 14:13:26 26 4
gpt4 key购买 nike

我正在学习 React 和 Redux,发现了以下我无法理解的问题,我存储了一个可能如下所示的配置对象:

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

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

现在,游戏 GameAGameB 正在使用 durationstrength Prop ,因此我可以执行以下操作:

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
}

最佳答案

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

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

选择器提供了内存派生值的好处,考虑到 react 生命周期方法的敏感性,这证明非常有用(如果不需要,为什么要多次进行此计算?)。

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

这是一个简短且非常简单的示例:

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了解更多信息。

虽然 reselect 的使用是为了从 redux 状态中获取值,但您可以将该库与您喜欢的任何数据结构/库/框架一起使用。

关于reactjs - 我可以操作 mapStateToProps 中的值吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48070180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com