【问题标题】:How to use Flux Container.create in Typescript 2.8如何在 Typescript 2.8 中使用 Flux Container.create
【发布时间】:2018-10-25 17:06:29
【问题描述】:

我正在尝试将我的 react/flux 项目从 typescript 2.2 更新到 2.8。

我使用 container.create 实用函数定义了以下商店:

import * as React from 'react';
import { Container } from 'flux/utils';

export let MyContainer = Container.create(class extends React.Component<props, state> {
    static getStores() {
        return [/* list of stores here*/]
    }

    static calculateState(prevState: state, props: props): state {
        return {hello: true}
    }

    render() {
        return <div>something</div>
    }
}, { withProps: true });

如果我导出这个组件并尝试使用它,我会收到以下错误:

TS2605: JSX element type 'Component&lt;props, ComponentState&gt;' is not a constructor function for JSX elements.

这在我使用 typescript 2.2 时运行良好,但更新后我在任何地方都出现错误,我尝试像这样使用容器组件。

我使用的是 @types/react 类型版本 15.0.28。 Here are the definitions for Flux Containers.

【问题讨论】:

标签: reactjs typescript flux


【解决方案1】:

显然从 typescript 2.6 开始会发生此错误。但我不确定是什么重大变化导致了这种行为,match 似乎没有。

根本原因是这样的:

let readOnlyOrVoid: Readonly<void | {}> // resolves to void | Readonly<{}>
let readOnlyOfAny: Readonly<any> // in 2.5 this resolves to any, in 2.6 it does not we still have Readonly<any>
readOnlyOfAny = readOnlyOrVoid; // valid in 2.5, not so in 2.6

React 相关,ComponentState 在 15.0.23 中定义为:

type ComponentState = {} | void ;

JSX.ElementClass(扩展React.Component&lt;any, any&gt;)的state 具有Readonly&lt;any&gt; 类型。

由于Container.create 将返回状态为ComponentState 的包装组件,因此我们恰好遇到了将Readonly&lt;void | {}&gt;(来自包装组件)分配给Readonly&lt;any&gt;(来自JSX.ElementClass 的定义)的问题

最简单的解决方案是将react 的类型更新为15.0.39,将ComponentState 的定义替换为:

type ComponentState = {};

【讨论】:

  • 感谢您的详细解释!
  • @theycallmemorty 不要忘记奖励赏金:D
猜你喜欢
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 2011-02-27
  • 2017-12-22
  • 2018-10-06
  • 2018-09-24
  • 1970-01-01
  • 2016-09-25
相关资源
最近更新 更多