我是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);
我不知道问题出在哪里。
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>
);
}