javascript - React-Redux mapStateToProps 与传递父 Prop

标签 javascript reactjs redux react-redux

这可能是一个有点幼稚的问题,但我是 react-redux 的新手,我正在边学边学。

上下文:假设我有一个 react-redux 应用程序。在我的顶级组件中,我在底部有这个:

function mapStateToProps({ auth }) {
  return { auth };
}

export default connect(mapStateToProps)(newComponent);

“auth”部分来 self 的 reducer index.js 文件:

import { combineReducers } from "redux";
import authReducer from "./authReducer";

export default combineReducers({
  auth: authReducer
});

现在这个组件可以访问 auth 附带的所有数据,在我的应用程序中它包含所有需要的用户信息。

随着我的应用程序变大,我意识到我需要来自其他组件中的 authReducer 的数据,这些组件比顶级组件低 1 或 2 层

我的问题是:将顶级组件与 auth reducer 连接起来并将必要的信息传递给子组件是否更好?如果向下 100 层的 child 需要来自 authReducer 的信息,我们是否仍会逐层向下传递?

或者我们会像上面那样将 authReducer 连接到需要它的每个组件吗?重复这样做会很昂贵吗?

最佳答案

文档涉及围绕此主题的最佳实践:link .相关部分:

The current suggested best practice is to categorize your components as “presentational” or “container” components, and extract a connected container component wherever it makes sense:

Emphasizing “one container component at the top” in Redux examples was a mistake. Don't take this as a maxim. Try to keep your presentation components separate. Create container components by connecting them when it's convenient. Whenever you feel like you're duplicating code in parent components to provide data for same kinds of children, time to extract a container. Generally as soon as you feel a parent knows too much about “personal” data or actions of its children, time to extract a container.

In fact, benchmarks have shown that more connected components generally leads to better performance than fewer connected components.

In general, try to find a balance between understandable data flow and areas of responsibility with your components.

关于javascript - React-Redux mapStateToProps 与传递父 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45873882/

相关文章:

javascript - react native : You attempted to set the key on an object that is meant to be immutable and has been frozen

javascript - 如何使用 Redux Saga 测试 API 请求失败?

javascript - 这是一种安全的方式吗? Redux React 身份验证

javascript - Node.js - 不是函数

javascript - 如何等到 jQuery 函数完成后再继续?

javascript - 默认选中的选择元素上的占位符选项

javascript - 如何使用 OLOO 模式在 javascript 中实现继承

javascript - 如何在React js中进行迭代并分成两组?

javascript - 调用 setState() 改变集合时,是否可以在 React 中返回一个空对象?

javascript - 过滤后保留数据对象