Redux/Saga/React 使用 mapDispatchToProps 使用 dispatch props 初始化一个组件

Redux/Saga/React initialize a component with dispatch props using mapDispatchToProps

我正在将 React 与 Redux 和 Saga 结合使用。我的组件需要在用户点击时发送一个动作,所以我使用 mapDispatchToProps 将动作映射到道具中。

如果我从其他组件使用该组件,IDE 会警告我需要传入此调度道具。但是我认为 dispatch props 应该自己初始化,所以我不需要从外部传入。

我理解正确吗?

下面的例子:我有一个 DispatchComponent 有一个 dispatch 道具。我想在 RootComponent 中使用 DispatchComponent。但是我必须在 RootComponent 中传入 sendAction 否则它将无法正确初始化。

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

并确保您正在导入默认组件(已连接的组件)