Leo*_*vdb 5 typescript reactjs redux redux-thunk react-redux
在我的子组件中,我正在定义MapDispatchToProps,将它们传递到connect中,并相应地定义一个接口PropsFromDispatch,该接口在React.Component Props接口中进行了扩展。现在,在我的父组件中,Typescript告诉我它缺少我在PropsFromDispatch中定义的属性。
这似乎并不完全荒谬,因为我将它们定义为React.Component Props接口的一部分,但是我希望'connect'能够像处理PropsFromState一样来处理它。不必从父组件传递到子组件,而是从州映射到道具。
/JokeModal.tsx
...
interface Props extends PropsFromState, PropsFromDispatch {
isOpen: boolean
renderButton: boolean
}
...
const mapDispatchToProps = (dispatch: Dispatch<any>):
PropsFromDispatch => {
return {
tellJoke: (newJoke: INewJoke) => dispatch(tellJoke(newJoke)),
clearErrors: () => dispatch(clearErrors())
}
}
interface PropsFromDispatch {
tellJoke: (newJoke: INewJoke) => void
clearErrors: () => void
}
...
export default connect(mapStateToProps, mapDispatchToProps)(JokeModal);
Run Code Online (Sandbox Code Playgroud)
/Parent.tsx
...
button = <JokeModal isOpen={false} renderButton={true} />
...
Run Code Online (Sandbox Code Playgroud)
在/Parent.tsx的这一行中,Typescript现在告诉我:
Type '{ isOpen: false; renderButton: true; }' is missing the
following properties from type 'Readonly<Pick<Props, "isOpen" |
"renderButton" | "tellJoke" | "clearErrors">>': tellJoke, clearErrors
ts(2739)
Run Code Online (Sandbox Code Playgroud)
有趣的是,我可以通过删除MapDispatchToProps并直接将动作直接传递给connect(包括动作创建者中已经调度的动作)来完全避免错误:
export default connect(mapStateToProps, { tellJoke, clearErrors })(JokeModal);
Run Code Online (Sandbox Code Playgroud)
不过,我想知道如何在这里使用MapDispatchToProps,以及为什么Typescript希望我将这些操作传递给子组件?
很高兴听到您的建议!
我能够重现您的问题,问题显然出在源代码中mapDispatchToProps函数的类型签名中,您可以看到它具有类型参数Action = AnyAction
export interface Dispatch<A extends Action = AnyAction> {
<T extends A>(action: T): T
}
Run Code Online (Sandbox Code Playgroud)
您的问题的解决方案是更改Dispatch<any>为Dispatch<AnyAction>:
const mapDispatchToProps = (dispatch: Dispatch<AnyAction>): PropsFromDispatch
Run Code Online (Sandbox Code Playgroud)
请注意,由于您使用的是redux-thunk,类型系统可能不允许您调用dispatchthunk,因此您可能必须通过调用来作弊
clearErrors: () => dispatch<any>(clearErrors());
Run Code Online (Sandbox Code Playgroud)
或者使用ThunkDispatch和进行冗长的键入ThunkAction。我这里有一个这样的输入示例:ThunkDispatch和相应的ThunkAction。请注意,我使用typesafe-actions。
| 归档时间: |
|
| 查看次数: |
1260 次 |
| 最近记录: |