在自定义 onclick 事件中触发 redux 调度

Fire redux dispatch in custom onclick event

我四处寻找但似乎无法找到 9 或理解)如何实现这一目标。

我有一个在点击时触发事件的按钮

<button onClick={TestClick}>Click Me </button>

TestClick 事件读取为:

let TestClick = (e) => {
    const Dispatch = useDispatch();
    let Num = Math.random()*10;
    Dispatch(Increment(num));
};

这会触发 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. 错误。

如何在用户函数内调度?

import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './actions';

    let TestClick = () => {
        const dispatch = useDispatch();
        let Num = Math.random() * 10;
        dispatch(increment(Num));
    };

function App() {
    const counter = useSelector((state) => state.counter);
    const isLoggedIn = useSelector((state) => state.isLogged);

    const dispatch = useDispatch();

    return (
        <div className="App">
            <h1>Counter {counter}</h1>
            <button onClick={() => dispatch(increment(5))}>+</button>
            <button onClick={() => TestClick()}>+Random</button>
            <button onClick={() => dispatch(decrement())}>-</button>
            {isLoggedIn ? <h3>Valueable info</h3> : ''}
        </div>
    );
}

export default App;

TestClick 移动到组件内部。为了防止处理程序引用在每次渲染时发生变化,请使用 useCallback

import { useCallback, useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './actions';

function App() {
    const counter = useSelector((state) => state.counter);
    const isLoggedIn = useSelector((state) => state.isLogged);

    const dispatch = useDispatch();

    const TestClick = useCallback(() => {
        let Num = Math.random() * 10;
        dispatch(increment(Num));
    }, []);

    return (
        <div className="App">
            <h1>Counter {counter}</h1>
            <button onClick={() => dispatch(increment(5))}>+</button>
            <button onClick={TestClick}>+Random</button>
            <button onClick={() => dispatch(decrement())}>-</button>
            {isLoggedIn ? <h3>Valueable info</h3> : ''}
        </div>
    );
}

export default App;

您不能在 React 组件或其他钩子之外使用钩子。

两种解决方案:

const useTestClick = () => {
  const dispatch = useDispatch();
  let num = Math.random() * 10;
  return () => dispatch(increment(num));
};

function App() {
  const testClick = useTestClick()

  /* ... */

  <button onClick={testClick}>+Random</button>
function App() {
  const dispatch = useDispatch();

  const testClick = useCallback(() => {
    let num = Math.random() * 10;
    return () => dispatch(increment(num));
  }, [])

  /* ... */

  <button onClick={testClick}>+Random</button>