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

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

问题描述

我正在尝试理解react-redux的连接方法,以及它作为参数所采用的函数。特别是 mapStateToProps()



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



这意味着目标组件所消耗的状态可能与存储在商店中的状态有着截然不同的结构。



<问:这可以吗?

问:这是预期的吗?

问:这是反模式吗?

解决方案

问:这可以吗?

答:是



问:这是预期的吗?

是的,这是预期的(如果你使用的是react-redux)。



问:这是反模式吗?

答:不,这不是反-pattern。



它被称为连接您的组件或使其变得聪明。这是设计的。



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



以这种方式思考:商店应该包含应用程序的整个状态。

应用程序,这可能包含嵌套多层深层的许多属性。

您不希望在每次调用时都使用它(昂贵)。



如果没有 mapStateToProps 或其中某些类似物,你会想要用另一种方式来改变你的状态以提高性能/简化。


I'm trying to understand the connect method of react-redux, and the functions it takes as parameters. In particular 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?

解决方案

Q: Is this ok?
A: yes

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

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.

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).

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天全站免登陆