升级到较新版本的TypeScript

时间:2017-06-04 20:25:18

标签: reactjs typescript

我最近从TypeScript 2.1进行了升级,并且所有较新的版本都开始出现以下错误,我的所有React组件都遵循我的示例中的模式。嵌套组件的这种模式在升级之前不会导致任何问题。

组件#1:

interface ISpinnerProps{
    showGlobalSpinner: boolean;
}

class SpinnerClass extends React.Component<ISpinnerProps, undefined> {
    render() {
         return (
         // Some markup
         )
    }
}

export const Spinner = connect((state: State) => {
  return {
    showGlobalSpinner: selectors.showGlobalSpinner(state),
  }
})(SpinnerClass)

组件#2:

interface IProps {
   loginStatus: fb.LoginStatus
}


class AppClass extends React.Component<IProps, undefined> {
    render() {
         return (
         // Some markup
         <Spinner/> // Error is thrown here.
         )
    }
}
export const App = connect(mapStateToProps, actionCreators)(AppClass)

这会导致错误: Type '{}' is not assignable to type 'Readonly<ISpinnerProps>'. Property 'showGlobalSpinner' is missing in type '{}

编译器希望我在父级中设置子级的属性,但这些属性由Redux处理。有没有人遇到类似的问题?

1 个答案:

答案 0 :(得分:4)

您需要做的是将您的道具分离为从redux(IMappedProps和IMappedActions)映射的道具和动作,以及您希望从父组件(IOwnProps)传递到组件的道具。

然后在你的连接功能中,你可以指定哪个道具。

export default connect<IMappedProps, IMappedActions, IOwnProps>(mapStateToProps, mapDistpatchToProps)(SpinnerClass);

在您的情况下,微调器组件只有一个从redux映射的prop。您的连接功能可能如下所示:

export default connect<ISpinnerProps, null, null>(mapStateToProps, null)(SpinnerClass);

为清楚起见,我建议将ISpnnerProps重命名为IMappedProps。

有关进一步参考,请参阅react-redux打字稿定义 - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-redux/index.d.ts

相关问题