在本教程中https://redux.js.org/advanced/exampleredditapi在包含containers/AsyncApp.js
的部分中,它们的代码看起来像
componentDidMount() {
const { dispatch, selectedSubreddit } = this.props
dispatch(fetchPostsIfNeeded(selectedSubreddit))
}
但我不知道他们在这做什么。我试图效仿他们的例子,除了在一个带有打字稿的项目中。目前我从chrome控制台获得此运行时错误
Uncaught TypeError: dispatch is not a functon
at ProxyComponent.componentDidMount (MyComponent.tsx?23ad:27)
我的组件代码如下所示
export interface MyProps {
prop1: any[]
}
type MyComponentProps = MyProps & DispatchProp;
class MyComponent extends React.Component<MyComponentProps, MyState> {
componentDidMount() {
const { dispatch } = this.props;
dispatch(fetchAsyncData());
}
render() {
return (
<div>
</div>
);
}
}
export { MyComponent };
dispatch函数用于在我的redux代码中调用异步操作。我尝试包含一些名为DispatchProps的东西来获取我的道具中的调度功能,但它显然没有用。这个派遣功能来自哪里?
你在哪里定义你的dispatch
功能?你是用连接做的吗?无论如何,您需要像使用MyProps一样定义DispatchProp界面
export interface MyProps {
prop1: any[]
}
export interface DispatchProp {
dispatch: () => void // unsure what the actual type of your dispatch function is
}
type MyComponentProps = MyProps & DispatchProp;
...
如果您尝试使用连接来定义您的道具,它将看起来像这样
function mapDispatchToProps(dispatch: Dispatch<any>): DispatchProp {
return {
dispatch: () =>
dispatch({ type: "some_action_type", payload: somePayload})
};
}