简体   繁体   English

可以将整个Redux状态对象传递给React组件吗?

[英]Is it ok to pass the entire Redux state object into a React component?

We have a component which needs access to Redux's store. 我们有一个组件需要访问Redux的商店。

import React from 'react'
import { connect } from 'react-redux'

const Component = (props) => {
   ... code ...
}

We've connected this componet to the store using connect . 我们使用connect这个组件连接到商店。

export default connect(mapStateToProps)(Component)

We now need to define mapStateToProps to pass as the first argument to connect . 我们现在需要定义mapStateToProps作为connect的第一个参数传递。

const mapStateToProps = state => ({ ...state })

Why or why not is this an acceptable approach to injecting the data into the component? 为什么或为什么不是将数据注入组件的可接受方法? Would this make this component rerender in every situation that triggers a render? 这是否会在触发渲染的每种情况下重新渲染此组件?

Documentation and examples welcome. 欢迎提供文档和示例。

Demo Application 演示应用程序

FYI: I'm doing it for the second part of this video and considering listing it as the final solution. 仅供参考:我正在为本视频的第二部分做这件事,并考虑将其列为最终解决方案。 Would love to know Stack's thoughts on this code. 很想知道Stack对这段代码的看法。

I think it is a bad idea to pass the entire Redux state into a component. 我认为将整个Redux状态传递给组件是个坏主意。

Although your component today uses all the variables of the store, in the future it can be a different situation. 虽然您的组件今天使用了商店的所有变量,但将来可能会出现不同的情况。

Imagine that in the future you or other people create many new components that handle its vars in the store. 想象一下,在未来,您或其他人会创建许多新的组件来处理商店中的变量。 You see? 你看? The first components would receive a lot unnecessarily data. 第一个组件会收到很多不必要的数据。

It will only rerender on the props the component actually uses, React is smart like that. 它只会对组件实际使用的道具进行重新渲染,React就像那样聪明。 However, my personal preference is to not pass the entire object, it might be easier to code, but is a lot less verbose. 但是,我个人的偏好是不传递整个对象,它可能更容易编码,但是不那么冗长。

const mapStateToProps = state => ({ ...state })

In this line of code, you have no idea what the component is going to use, which makes your code way less readable, I also like to have control over the naming, that's why I prefer 在这行代码中,您不知道该组件将使用什么,这会使您的代码更不易读取,我也想控制命名,这就是我更喜欢的原因

const mapStateToProps = state => ({ 
  primary,                                    
  secondary,
  myComponentActive: active                                   
})

Now, when someone is reading your code, he knows exactly what's going on. 现在,当有人正在阅读您的代码时,他确切地知道发生了什么。

This also gives you a better overview if you ever want to change over to React Hooks, omitting the mapStateToProps object. 如果您想要切换到React Hooks,省略mapStateToProps对象,这也为您提供了更好的概述。 Even though there is still discussion whether Hooks are the future, I find it be very convenient. 即使仍然在讨论Hooks是否是未来,我觉得它非常方便。 That is not of much use for your video, although you might discuss the possibility of changing over! 虽然您可能会讨论转换的可能性,但这对您的视频没什么用处!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM