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

在自定义挂钩中访问Redux状态?,redux,react-hooks,Redux,React Hooks,我需要一个使用Redux状态的自定义钩子。如果要将状态从React组件传递给函数,它将如下所示: 自定义挂钩: function useMyCustomHook(state) { const { message } = state; const handleClick = () => { if(environment_variable) { // do something with message } else { // do someth

我需要一个使用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的状态,这有点痛苦。是否可以直接在自定义挂钩中访问状态?

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

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

import { useSelector } from 'react-redux';
function useMyCustomHook(state) {
  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>
}

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

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

import { useSelector } from 'react-redux';
function useMyCustomHook(state) {
  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>
}

如果Redux提供了一个钩子来获取状态,那么在钩子中使用钩子。如果Redux提供了一个钩子来获取状态,那么在钩子中使用钩子。