【发布时间】: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