在基于类的组件中使用分派会给出无效的挂钩调用错误

时间:2020-02-12 08:25:01

标签: reactjs typescript redux react-redux

我是react-redux的新手。我有这段代码,我正在使用reactreduxTypeScript。 在此代码中,使用基于类的组件,并且我想使用分派来调用操作以递增counter的值,但是,这给了我以下错误。

Error: 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 from 'react';
import { connect, useDispatch } from 'react-redux';
import { Dispatch } from 'redux';
import { increment, decrement } from '../actions/counterAction';

interface IHome {
    counter: 0
}

class Home extends React.Component<IHome> {
    render() {
        const dispatch = useDispatch();

        return (
            <div>
                This is the home page {this.props.counter}
                <button onClick={()=>dispatch(increment)}>+</button>
                <button>-</button>
            </div>
        );
    }
}

const mapStateToProps = (state: IHome) => {
    return {
        counter: state.counter
    }
}

const mapDispatchToProps = (dispatch: Dispatch) => {
    return {
        increment: () => dispatch(increment()),
        decrement: () => dispatch(decrement())
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Home);

我不知道问题出在哪里。

2 个答案:

答案 0 :(得分:2)

useDispatch()挂钩只能在功能组件中使用。

由于已经连接了组件,因此已经通过decrement将redux操作(incrementprops)传递给了组件。

但是,您将需要修复组件的props接口,如目前,TypeScript认为唯一有效的prop是counter

interface StoreProps {
  counter: number
}

interface DispatchProps {
  increment: () => void;
  decrement: () => void;
}

type IHome = DispatchProps & StoreProps;

class Home extends React.Component<IHome> {
    render() {
        const { counter, increment, decrement } = this.props;
        return (
            <div>
                This is the home page {counter}
                <button onClick={()=>increment()}>+</button>
                <button>-</button>
            </div>
        );
    }
}

答案 1 :(得分:1)

Home是一个类组件。如果要在其中使用钩子,则必须将其更改为功能组件。在这种情况下,您可以摆脱connect和map ...函数调用,并使用store的useStore挂钩。

export default const Home: React.FC<IHome> = () => {
  const dispatch = useDispatch();
  const store = useStore()

  return (
      <div>
          This is the home page {store.getState().counter}
          <button onClick={() => dispatch(increment())}>+</button>
          <button>-</button>
      </div>
  );
}