理解 React-Redux 和 mapStateToProps() [英] Understanding React-Redux and mapStateToProps()

查看:36
本文介绍了理解 React-Redux 和 mapStateToProps()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解 react-redux 的 connect 方法,以及它作为参数的函数.特别是 mapStateToProps().

I'm trying to understand the connect method of react-redux, and the functions it takes as parameters. In particular mapStateToProps().

按照我的理解,mapStateToProps 的返回值将是从状态派生的对象(因为它存在于商店中),其键将传递给您的目标组件(组件连接应用于)作为道具.

The way I understand it, the return value of mapStateToProps will be an object derived from state (as it lives in the store), whose keys will be passed to your target component (the component connect is applied to) as props.

这意味着您的目标组件使用的状态可能与存储在您的商店中的状态具有截然不同的结构.

This means that the state as consumed by your target component can have a wildly different structure from the state as it is stored on your store.

问:这样可以吗?
问:这是预期的吗?
问:这是一种反模式吗?

Q: Is this OK?
Q: Is this expected?
Q: Is this an anti-pattern?

推荐答案

问:这样好吗?
答:是的

问:这是预期的吗?
是的,这是意料之中的(如果您使用的是 react-redux).

Q: Is this expected?
Yes, this is expected (if you are using react-redux).

问:这是反模式吗?
A:不,这不是反模式.

Q: Is this an anti-pattern?
A: No, this is not an anti-pattern.

这称为连接"您的组件或使其变得智能".这是设计使然.

It's called "connecting" your component or "making it smart". It's by design.

它允许您将组件与状态分离额外的时间,从而增加代码的模块化.它还允许您将组件状态简化为应用程序状态的一个子集,这实际上有助于您遵守 Redux 模式.

It allows you to decouple your component from your state an additional time which increases the modularity of your code. It also allows you to simplify your component state as a subset of your application state which, in fact, helps you comply with the Redux pattern.

这样想:商店应该包含应用程序的整个状态.
对于大型应用程序,这可能包含嵌套许多层的数十个属性.
您不想在每次通话时都拖着所有这些(昂贵).

Think about it this way: a store is supposed to contain the entire state of your application.
For large applications, this could contain dozens of properties nested many layers deep.
You don't want to haul all that around on each call (expensive).

如果没有 mapStateToProps 或类似的东西,你会很想用另一种方式来分割你的状态来提高性能/简化.

Without mapStateToProps or some analog thereof, you would be tempted to carve up your state another way to improve performance/simplify.

这篇关于理解 React-Redux 和 mapStateToProps()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆