【发布时间】:2020-02-12 08:25:01
【问题描述】:
我是react-redux 的新手。我有这个代码,我正在使用react、redux 和TypeScript。
在此代码中使用基于类的组件,我想使用 dispatch 调用操作以增加 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);
我不知道问题出在哪里。
【问题讨论】:
标签: reactjs typescript redux react-redux