【发布时间】:2020-02-01 11:07:12
【问题描述】:
我正在使用 React + Redux 处理我的第一个项目,当我尝试在 componentDidMount 部分中调度一个函数时遇到了一些问题。我尝试关注文档中的 Reddit API example 项目,但由于他们使用 JavaScript 而我使用的是 TypeScript,所以并非所有内容都相同。
这是我试图实现这一目标的 React 组件:
export class EducationComponent extends Component {
constructor(props: any) {
super(props);
}
componentDidMount() {
const { dispatch, getUser } = this.props;
dispatch(getUser());
}
public render() {
return (
<Content className="component">
<Demo/>
</Content>
);
}
}
function mapStateToProps(state: State) {
const { isLoaded, isFetching, user } = state.userProfile;
return {
user,
isFetching,
isLoaded
}
}
export default connect(mapStateToProps)(EducationComponent)
export const Education = (EducationComponent);
我在const { dispatch, getUser } = this.props; 行中收到以下错误:
Error:(16, 17) TS2339: Property 'dispatch' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
Error:(16, 27) TS2339: Property 'getUser' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
如果有任何不确定,可以在这里找到该项目:https://github.com/jLemmings/GoCVFrontend
这是完成这项工作的正确方法还是有更好的选择?
谢谢
编辑当前状态:
const {Content} = Layout;
export class EducationComponent extends Component {
constructor(props: any) {
super(props);
}
componentDidMount() {
this.props.userAction();
}
public render() {
return (
<Content className="component">
<Demo/>
</Content>
);
}
}
const mapDispatchToProps = (dispatch: Dispatch) => bindActionCreators({
userAction: action.getUser,
}, dispatch);
function mapStateToProps(state: State) {
const { isLoaded, isFetching, user } = state.userProfile;
return {
user,
isFetching,
isLoaded
}
}
export default connect(mapStateToProps, mapDispatchToProps)(EducationComponent)
最终编辑(让它工作):
interface MyProps {
getUser: () => void
}
interface MyState {
userAction: ThunkAction<Promise<void>, {}, {}, AnyAction>
}
export class EducationComponent extends Component<MyProps, MyState> {
static defaultProps = {getUser: undefined};
constructor(props: any) {
super(props);
}
componentDidMount() {
this.props.getUser()
}
public render() {
return (
<Content className="component">
<Demo/>
</Content>
);
}
}
const mapDispatchToProps = (dispatch: ThunkDispatch<{}, {}, any>, ownProps: MyProps) => {
return {
getUser: () => {
dispatch(getUser());
}
}
}
function mapStateToProps(state: State) {
const {isLoaded, isFetching, user} = state.userProfile;
return {
user,
isFetching,
isLoaded
}
}
export default connect(mapStateToProps, mapDispatchToProps)(EducationComponent)
【问题讨论】:
-
这些是打字稿错误。
-
嗨,试试这个存储库,https://github.com/senthilmca90/mern-crud。你试试
client文件夹反应代码。
标签: reactjs typescript redux react-redux