在自定义钩子中访问 Redux 状态?

Posted

技术标签:

【中文标题】在自定义钩子中访问 Redux 状态?【英文标题】:Access Redux state in custom hook? 【发布时间】:2020-08-28 15:41:04 【问题描述】:

我需要一个使用 Redux 状态的自定义钩子。如果你要将状态从 React 组件传递给函数,它看起来像:

自定义钩子:

function useMyCustomHook(state) 
  const  message  = state;

  const handleClick = () => 
    if(environment_variable) 
      // do something with message
     else 
      // do something else with message 
    
  

  return handleClick;

我的组件:

const MyComponent = ( state ) => 
  return <button onClick=()=> useMyCustomHook(state) >Go</button>

每次都必须从 React 组件传递 Redux 的状态有点痛苦。是否可以直接在自定义钩子中访问状态?

【问题讨论】:

如果 Redux 提供了一个钩子来获取状态,那么在你的钩子中使用一个钩子。 【参考方案1】:

使用最新版本的 react-redux,您可以使用 useSelector 钩子。

还要注意,不应该在处理程序上调用钩子

import  useSelector  from 'react-redux';
function useMyCustomHook() 
  const message = useSelector(state => state.message);

  const handleClick = () => 
    if(environment_variable) 
      // do something with message
     else 
      // do something else with message 
    
  

  return handleClick;

它会像这样使用

const MyComponent = ( state ) => 
  const handleClick = useMyCustomHook();
  return <button onClick=handleClick>Go</button>

【讨论】:

自定义钩子的“state”参数应该是不必要的

以上是关于在自定义钩子中访问 Redux 状态?的主要内容,如果未能解决你的问题,请参考以下文章

在自定义 serviceWorker 中调度 redux 操作

如何使用 Mock Service Worker 在自定义钩子中模拟获取?

useEffect 在自定义钩子中使用 ref 缺少依赖项警告

创建永不重建的自定义钩子

React Hooks:确保 useEffect 仅在自定义钩子的数组参数内容更改时运行的惯用方法

React 中的状态管理