gpt4 book ai didi

javascript - React-Redux mapStateToProps 与传递父 Prop

转载 作者:可可西里 更新时间:2023-11-01 02:34:35 26 4
gpt4 key购买 nike

这可能是一个有点幼稚的问题,但我是 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/

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