我正在尝试使用 useDispatch
在我的组件的渲染函数中。
import { useDispatch } from 'react-redux';
我有一个输入试图在
onChange
上使用 DispatchonChange={() => useDispatch()(update("test"))}
当 onChange 被触发时,我收到此错误:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
import React, {
Component
} from 'react';
import {
useDispatch
} from 'react-redux';
import {
update
} from '../store/actions';
class Something extends Component {
render() {
return (<input onChange={() => useDispatch()(update("test"))}/>)
}
}
export default Something;
最佳答案
问题是你在 render
中使用它在类组件中。您不能在类组件中使用钩子(Hook)。这就是为什么错误消息说
Invalid hook call. Hooks can only be called inside of the body of a function component.
(我的重点)。类组件不是函数组件。 (这有点容易错过,如果可能的原因列表特别提到了类组件,那就太好了。)
所以你想让它成为一个函数组件:
import React, {
Component
} from 'react';
import {
useDispatch
} from 'react-redux';
import {
update
} from '../store/actions';
function Something() { // ***
return <input onChange={() => useDispatch()(update("test"))}/>; // ***
} // ***
export default Something;
还要注意 the documentation 中的警告以上将导致不必要的渲染,您应该使用
useCallback
:import React, {
Component,
useCallback
} from 'react';
import {
useDispatch
} from 'react-redux';
import {
update
} from '../store/actions';
function Something() {
const dispatch = useDispatch(); // ***
const handleChange = useCallback( // ***
() => dispatch(update("test")), // ***
[dispatch] // ***
); // ***
return <input onChange={handleChange}/>; // ***
}
export default Something;
关于reactjs - React.js - Redux 钩子(Hook)无效的钩子(Hook)调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58395299/