【问题标题】:In a React/Redux project how to make Typescript aware of property passed by redux's connect decorator?在 React/Redux 项目中,如何让 Typescript 知道 redux 的连接装饰器传递的属性?
【发布时间】:2017-11-12 01:00:23
【问题描述】:

鉴于以下组件,我收到一个关于缺少 isUpdating 道具的错误。我该如何解决?

错误:(87, 27) TS2322:Type '{ name: "Fred"; }' 不可分配给类型 'IntrinsicAttributes & IntrinsicClassAttributes> & Reado...'。 键入'{名称:“弗雷德”; }' 不可分配给类型“只读”。 类型 '{ name: "Fred"; 中缺少属性 'isUpdating'; }'。

interface ContaineeProps {
  name: string;
  isUpdating: string;
}

const Containee = (props: ContaineeProps) => <span>{props.name}</span>;

interface MapStateToProps {
  isUpdating: boolean;
}
const mapStateToProps = state => ({ isUpdating: state.years.yearsUpdating });

const ConnectedContainee = connect<MapStateToProps, null, ContaineeProps>(mapStateToProps)(Containee);


interface Container {
  name: string;
}

class Container extends React.Component<Container, {}> {
  render() {
    return (
      <ConnectedContainee name="Fred" />
    )
  }
}

编辑:这个问题更多的是关于 redux/react/typescript 应用程序中的最佳实践,而不是关于这个错误的原因。我是否总是必须在两个地方(组件的 props 接口和 mapStateToProps 函数的接口)指定所需的 props 类型信息?

【问题讨论】:

  • 什么是 VehiclesFormProps?
  • @OliverCharlesworth 好废话,我以为我从我的实际组件中复制/粘贴/编辑一个简化的示例做了如此仔细的工作。原来我真的很烂! (修正了我的例子)

标签: reactjs typescript redux react-redux


【解决方案1】:

您收到的编译错误是正确的。鉴于您的ContaineeProps 包含一个属性isUpdating,您的组件在使用它时需要传递此属性。

例如&lt;ConnectedContainee name="Fred" isUpdating="testing" /&gt;

鉴于您的问题,我想知道isUpdating 是否应该在ContaineeProps 中?如果不是,那么只需将其删除,编译错误就会消失。

如果它打算在那里,那么我建议给它一个不同的名称,因为你的MapStateToProps 接口中已经有一个isUpdating 属性。

更新

如果我正确理解您的评论,您已将 isUpdating 属性添加到您的 ContaineeProps 以便能够在您的组件中访问它。为此,您不需要将属性添加到两个 prop 接口,我实际上认为这不会起作用...

你需要做的是组合你的接口,这样你的组件就可以访问包含从父组件传入的 props 和从 redux 映射的 props 的接口。

这是一个例子:

interface AllProps extends MapStateToProps, ContaineeProps {}

const Containee = (props: AllProps) => <span>{props.name} {props.isUpdating}</span>;

const Containee = (props: ContaineeProps & MapStateToProps) => <span>{props.name} {props.isUpdating}</span>;

props.isUpdating 现在指的是从 redux 存储中映射的属性。如果您还想在本地存储 isUpdating 值,您将使用组件本地状态。

【讨论】:

  • Containee 组件需要 isUpdating 属性。它永远不会被“手动”传递给它,它总是通过调用连接来自 redux 存储。我知道我可以删除ContaineeProps 中的道具,但是我必须在两个地方维护组件的类型信息...MapStateToPropsContaineeProps。如果这是通常在 redux/react/typescript 应用程序中完成的方式,那么就这样吧,它似乎不是最理想的。
  • @DustinWyatt,我已更新我的答案以反映您的评论。希望这会有所帮助。
猜你喜欢
  • 1970-01-01
  • 2018-04-02
  • 2019-03-07
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多