TypeScript与Redux容器作斗争

TypeScript与Redux容器作斗争,第1张

TypeScript与Redux容器作斗争

您上一个示例在正确的轨道上。您还需要定义一个

MyOwnProps
接口,然后键入
connect
函数。

使用以下类型:https :
//github.com/DefinitelyTyped/DefinitelyTyped/blob/master/react-redux/react-
redux.d.ts
,您可以执行以下 *** 作

interface MyProps {  section: string;  name: string;  selected: boolean;  onSelect: (name: string) => void;}interface MyStateProps {  name: string;  selected: boolean;}interface MyDispatchProps {  onSelect: (name: string) => void;}interface MyOwnProps {  section: string;}class MyComponent extends React.Component<MyProps, {}> { }function mapStateToProps(state: MyState): MyStateProps { }function mapDispatchToProps(dispatch: IDispatch): MyDispatchProps { }const MyContainer = connect<MyStateProps, MyDispatchProps, MyOwnProps>(  mapStateToProps,  mapDispatchToProps)(MyComponent);

这也让你输入

ownProps
mapStateToProps
mapDispatchToProps
,如

function mapStateToProps(state: MyState, ownProps: MyOwnProps): MyStateProps

只要定义了调度,状态和ownProps类型,就不需要为MyProps类型定义交集类型。这样,您可以将MyProps保留在自己的位置,并让容器(或没有容器使用组件的地方)根据需要应用道具。我想这取决于您和您的用例-
如果您定义

MyProps = MyStateProps & MyDispatchProps &MyOwnProps
,则将其绑定到一个特定的容器,该容器的灵活性较差(但不太冗长)。

作为解决方案,它非常冗长,但是我认为没有办法告诉Typescript所需的道具的不同部分将在不同的地方组装

connect
并将它们绑在一起。

另外,为了简单起见,为了简单起见,我通常会带可选的道具,因此在使用这种方法时,我没有太多经验可以分享。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5662501.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存