【问题标题】:Redux/Saga/React initialize a component with dispatch props using mapDispatchToPropsRedux/Saga/React 使用 mapDispatchToProps 使用 dispatch props 初始化组件
【发布时间】:2020-05-28 15:25:17
【问题描述】:

我将 React 与 Redux 和 Saga 一起使用。我的组件需要在用户点击时调度一个动作,所以我使用mapDispatchToProps 将动作映射到道具。

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

我的理解正确吗?

下面的示例:我有一个DispatchComponent,它有一个调度道具。我想在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);

【问题讨论】:

  • 您是否在RootComponent.tsx 中使用默认导入? (import DispatchComponent from './DispatchComponent')

标签: reactjs react-redux redux-saga


【解决方案1】:

您可以为连接的道具添加类型 https://redux.js.org/recipes/usage-with-typescript/#typing-the-connect-higher-order-component

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

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2018-11-18
    • 2018-05-19
    • 2016-10-17
    • 2019-01-16
    • 2020-10-15
    • 2019-12-19
    • 1970-01-01
    相关资源
    最近更新 更多