【问题标题】:ReactJS good practices using Hooks and Redux. Should I use useSelector in each component, or I should pass via props?ReactJS 使用 Hooks 和 Redux 的良好实践。我应该在每个组件中使用 useSelector,还是应该通过 props 传递?
【发布时间】:2020-08-22 23:24:25
【问题描述】:

我应该在每个子组件中使用相同的 useSelector 还是应该通过 props 传递 useSelector?

以下两个示例都有效,我只想知道最佳做法是什么。

通过 props 传递的示例:

const FatherComponent = () => {
 const userId = useSelector((state) => state.user.id);

 return (
   <ChildComponent userId={userId} />
 )
}

const ChildComponent = ({userId}) => {
 return (
 <>{userId}</>
)
}

或重复使用选择器的示例:

const FatherComponent = () => {
 const userId = useSelector((state) => state.user.id);

 return (
  <ChildComponent />
 )
}

const ChildComponent = () => {
 const userId = useSelector((state) => state.user.id);

 return (
  <>{userId}</>
 )
}

【问题讨论】:

标签: javascript reactjs ecmascript-6 react-redux


【解决方案1】:

希望有更多 UI 组件订阅 Redux 存储并以更精细的级别读取数据

为了完整起见,以上是redux官方网站的推荐。

感谢指向 cmets 部分页面的 Nicholas Tower。

希望有更多 UI 组件订阅 Redux 存储,并且 更细粒度地读取数据。这通常会导致更好的 UI 性能,因为在给定的情况下需要渲染的组件更少 状态变化。

例如,不仅仅是连接一个组件和 读取整个用户数组,检索到一个列表 所有用户 ID,将列表项呈现为 ,以及 已连接并从中提取自己的用户条目 商店。

这适用于 React-Redux connect() API 和 useSelector() 钩子。

来自链接 - https://redux.js.org/style-guide/style-guide#connect-more-components-to-read-data-from-the-store

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 2020-03-29
    相关资源
    最近更新 更多