我正在将React与Redux和Saga一起使用。当用户单击时,我的组件需要调度一个动作,因此我使用mapDispatchToProps
将动作映射为道具。
如果我使用其他组件中的该组件,IDE会警告我我需要传递此调度道具。但是我认为调度道具应该自己初始化,所以我不需要从外面传入。
我理解正确吗?
以下示例:我有一个带有调度道具的DispatchComponent
。我想在DispatchComponent
中使用RootComponent
。但是,我必须在sendAction
中传递RootComponent
,否则它将无法正确初始化。
DispatchComponent.tsx
type DispatchProps = {
sendAction: () => void;
};
export const DispatchComponent: React.FunctionComponent<DispatchProps> = (props) => {
return (
<Button onClick={props.sendAction}>Click me</Button>
);
};
const mapDispatchToProps = (dispatch: Dispatch<Action>) => ({
sendAction: () =>
dispatch(setAction)
});
export default connect(
null,
mapDispatchToProps)
(DispatchComponent);
RootComponent.tsx
export const RootComponent = () => {
return (
<DispatchComponent/> // IDE here will warn me that I need to pass in `sendAction`
);
};
export default connect(
null,
null)
(RootComponent);
您可以为连接的道具添加类型https://redux.js.org/recipes/usage-with-typescript/#typing-the-connect-higher-order-component
并确保要导入默认组件(连接的组件)