reactjs - React.js - Redux 钩子(Hook)无效的钩子(Hook)调用

标签 reactjs typescript redux react-redux

我正在尝试使用 useDispatch在我的组件的渲染函数中。

import { useDispatch } from 'react-redux';

我有一个输入试图在 onChange 上使用 Dispatch
onChange={() => 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:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. 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/

相关文章:

javascript - React 应用程序尝试绑定(bind)到 View 时出错

typescript - 在 typescript 2.0 中搜索类型定义的规范方法

jquery - 错误 TS2339 : Property 'modal' does not exist on type 'JQuery'

javascript - Redux mapDispatchToProps 未获得正确的有效负载

reactjs - 通过 ref 访问公开的方法

javascript - sessionStorage.getItem null 在 react 中

arrays - react .js : How to properly append multiple items to an array state using its use-state hook setter?

npm - Windows 上 npm typescript@1.4.1 的编译问题

typescript - 如何将使用 typesafe-actions createAsyncAction 创建的操作传递给生成具有正确类型的 redux-observable 史诗的函数?

javascript - 使用 Split Map 时 JSX 额外的空白