【问题标题】:Access Redux state in custom hook?在自定义钩子中访问 Redux 状态?
【发布时间】: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 提供了一个钩子来获取状态,那么在你的钩子中使用一个钩子。

标签: redux react-hooks


【解决方案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”参数应该是不必要的
猜你喜欢
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2022-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多