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

问题描述 投票:1回答:1

我是React-redux的新手。我有这段代码,我正在使用react,redux和Typescript。在此代码中,使用基于类的组件,并且我想使用分派来调用操作以增加计数器的值。但这给了我错误。

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

我不知道问题出在哪里。

reactjs typescript redux react-redux
1个回答
1
投票

Home是一个类组件。如果要在其中使用钩子,则必须将其更改为功能组件:

const Home: React.FC<IHome> = ({counter}) => {
  const dispatch = useDispatch();

  return (
      <div>
          This is the home page {counter}
          <button onClick={()=>dispatch(increment)}>+</button>
          <button>-</button>
      </div>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.