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



我四处寻找,但似乎找不到(或不明白(如何实现这一点。

我有一个按钮,可以在点击时触发事件

<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;

不能在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>

在组件内移动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;

相关内容

  • 没有找到相关文章

最新更新