我应该使用 useselector/useDispatch 而不是 mapStateToProps [英] Should I use useselector/useDispatch instead of mapStateToProps

查看:48
本文介绍了我应该使用 useselector/useDispatch 而不是 mapStateToProps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建 React 应用程序时,如果我使用钩子 useSelector,我需要遵守钩子调用规则(只能从功能组件的顶层调用它).如果我使用 mapStateToProps,我会在 props 中获取状态,我可以在任何地方使用它而不会出现任何问题...... useDispatch

也有同样的问题

mapStateToProps 相比,使用钩子除了节省代码行之外还有什么好处?

解决方案

可以从组件中的任何位置读取和更改 Redux 存储状态,包括回调.每当存储状态发生更改时,组件都会重新呈现.当组件重新渲染时, useSelector 再次运行,并为您提供更新的数据,以后可以在您想要的任何地方使用.下面是一个例子以及在回调中使用 useDispatch 的例子(在根级别赋值之后):

function Modal({ children }) {const isOpen = useSelector(state => state.isOpen);const dispatch = useDispatch();函数 handleModalToggled() {//在回调中使用来自商店状态的更新数据如果(isOpen){//写入状态,导致重新渲染调度({类型:CLOSE_MODAL"});返回;}//写入状态,导致重新渲染调度({类型:OPEN_MODAL"});}//在渲染中使用来自存储状态的更新数据返回 (isOpen ? (<div>{孩子们}<button onClick={handleModalToggeled}>关闭模态</button>

) : (<button onClick={handleModalToggeled}>打开模态</button>););}

mapStateToProps/mapDispatchToProps 没有什么是 useSelector 和 useDispatch 钩子做不到的.

话虽如此,这两种方法之间存在一些值得考虑的差异:

  1. 解耦:通过mapStateToProps,容器逻辑(存储数据注入组件的方式)与视图逻辑(组件渲染)分离.useSelector 代表了一种新的、不同的思考连接组件的方式,认为组件之间的解耦更重要,并且组件是自包含的.哪个更好?结论:没有明确的赢家.来源
  2. DX(开发者体验):使用 connect 函数通常意味着每个连接的组件都应该有另一个额外的容器组件,其中使用 useSelector 和 useDispatch 钩子是相当困难的.结论:钩子有更好的 DX.
  3. 陈旧的道具"和Zombie child":useSelector 有一些奇怪的边缘情况,如果它依赖于 props,useSelector 可以在最新更新的 props 进来之前运行.这些大多是罕见且可以避免的边缘情况,但它们已经被解决了在较旧的连接版本中.结论:connect 比 hooks 稍微稳定一些.来源
  4. 性能优化:两者都以不同的方式支持性能优化.connect 有一些高级技术,使用隐藏在 connect 函数中的合并道具和其他选项.useSelector 接受第二个参数 - 一个用于确定状态是否已更改的相等函数.结论:两者都非常适合高级情况下的性能.
  5. 类型:使用带有连接的打字稿是一场噩梦.我记得自己为每个连接的组件(OwnProps、StateProps、DispatchProps)狂热地编写了三个 props 接口.Redux hooks 以一种相当直接的方式支持类型.结论:使用钩子更容易处理类型.
  6. React 的未来:Hooks 是 React 的未来.这可能听起来像是一个奇怪的论点,但随着并发模式"的出现,生态系统的改变就在眼前.和服务器组件".虽然未来的 React 版本仍将支持类组件,但新功能可能仅依赖于钩子.这种变化当然也会影响生态系统中的第三方库,比如 React-Redux.结论:钩子更能证明未来.

TL;DR - 最终结论:每种方法都有其优点.Connect 更成熟,出现奇怪错误和边缘情况的可能性较小,并且具有更好的关注点分离.Hooks 更易于阅读和编写,因为它们位于使用它们的地方附近(全部在一个独立的组件中).此外,它们更易于与 TypeScript 一起使用.最后,它们很容易升级到未来的 React 版本.

When creating a React app, if I use the hook useSelector, I need to adhere to the hooks invoking rules (Only call it from the top level of a functional component). If I use the mapStateToProps, I get the state in the props and I can use it anywhere without any issues... Same issue for useDispatch

What are the benefits of using the hook besides saving lines of code compared to mapStateToProps?

解决方案

Redux store state can be read and changed from anywhere in the component, including callbacks. Whenever the store state is changed the component rerenders. When the component rerenders, useSelector runs again, and gives you the updated data, later to be used wherever you want. Here is an example of that and a usage of useDispatch inside a callback (after an assignment in the root level):

function Modal({ children }) {
  const isOpen = useSelector(state => state.isOpen);
  const dispatch = useDispatch();
  function handleModalToggeled() {
    // using updated data from store state in a callback
    if(isOpen) {
      // writing to state, leading to a rerender
      dispatch({type: "CLOSE_MODAL"});
      return;
    }
    // writing to state, leading to a rerender
    dispatch({type: "OPEN_MODAL"});
  }
  // using updated data from store state in render
  return (isOpen ? (
      <div>
        {children}
        <button onClick={handleModalToggeled}>close modal</button>
      </div>
    ) : (
      <button onClick={handleModalToggeled}>open modal</button>
    );
  );
}

There is nothing you can do with mapStateToProps/mapDispatchToProps that you can't do with the useSelector and useDispatch hooks as well.

With that said, there are a couple of differences between the two methods that are worth considering:

  1. Decoupling: with mapStateToProps, container logic (the way store data is injected into the component) is separate from the view logic (component rendering). useSelector represents a new and different way of thinking about connected components, arguing that the decoupling is more important between components, and that components are self contained. Which is better? Verdict: no clear winner. source
  2. DX (Developer experience): using the connect function usually means there should be another additional container component for each connected component, where using the useSelector and useDispatch hooks is quite strait forward. Verdict: hooks have better DX.
  3. "Stale props" and "Zombie child": there are some weird edge cases with useSelector, if it depends on props, where useSelector can runs before the newest updated props come in. These are mostly rare and avoidable edge cases, but they had been already worked out in the older connect version. verdict: connect is slightly more stable than hooks. source
  4. Performance optimizations: both support performance optimizations in different ways. connect has some advanced techniques, using merge props and other options hidden in the connect function. useSelector accepts a second argument - an equality function to determine if the state has changed. verdict: both are great for performance in advanced situations.
  5. Types: using typescript with connect is a nightmare. I remember myself feverishly writing three props interfaces for each connected component (OwnProps, StateProps, DispatchProps). Redux hooks support types in a rather straight forward way. verdict: types are significantly easier to work with using hooks.
  6. The future of React: Hooks are the future of react. This may seam like an odd argument, but change to the eco system is right around the corner with "Concurrent mode" and "Server components". While class components will still be supported in future React versions, new features may rely solely on hooks. This change will of course also affect third party libraries in the eco system, such as React-Redux. verdict: hooks are more future proof.

TL;DR - Final verdict: each method has its merits. Connect is more mature, has less potential for weird bugs and edge cases, and has better separation of concerns. Hooks are easier to read and write, as they are collocated near the place where they are used (all in one self contained component). Also, they are easier to use with TypeScript. Finally, they will easily be upgradable for future react versions.

这篇关于我应该使用 useselector/useDispatch 而不是 mapStateToProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆