扩展已连接的有状态已连接组件

时间:2019-06-17 14:14:26

标签: reactjs typescript redux

我想创建一个具有其自身状态和属性的基本Redux组件。当我以通用方式扩展它时,我想将扩展对象的属性和状态也与基础合并。该组件必须与我的Redux商店连接。

我创建了一些代码段,这些代码段适用于属性,但不适用于状态。

BaseComponent:

import * as React from "react";

import { connect } from "react-redux";
import { IRootState } from "../../../Store/ApplicationStore";

interface IComponentStoreProps {
    storeProp?: boolean;
}

interface IComponentOwnState {
    myState?: string | number;
}

class BaseComponent<Props, State> extends React.Component<Props & IComponentStoreProps, State & IComponentOwnState> {
    constructor(props: Props & IComponentStoreProps) {
        super(props);
    }
}

export const BaseComponentConnected = <Props, State>() => {
    return connect(
        (state: IRootState): any => {
            return {
                storeProp: state.global.tfsRelatedData.isLoaded
            };
        }
    )(BaseComponent as new () => BaseComponent<Props & IComponentStoreProps, State & IComponentOwnState>);
};

ExtendedComponent:

interface IComponentOwnState {
    fieldValue: string;
}

interface IComponentStoreProps {
    isLoaded: boolean;
}

class ExtendedComponent extends BaseComponentConnected<IComponentStoreProps, IComponentOwnState>() {
 //this.props.isLoaded   -> exists
 //this.props.storeProp  -> exists
 //this.state            -> undefined
}

如何在继承的类中创建合并状态对象?

如果我导出未连接的组件,则一切正常,我想对连接的组件进行相同的操作。

1 个答案:

答案 0 :(得分:0)

您对我的尝试感到困惑。您正在尝试让“父亲”组件对“儿子”组件进行更改-这违背了国家与道具的全部宗旨。组件的状态仅与它有关,而其他任何人都不能访问它,更不用说对其进行修改了。按照React Documentation

  

React具有强大的组合模型,我们建议使用组合而不是继承来在组件之间重用代码。

如果您希望提供附加值作为组件的道具,则建议使用Higher-Order Componentsrender props或自定义hook的模式。

如果您坚持使用继承模型,那么我的回答是-您应该自己合并状态,可能在组件的构造函数中。我在代码的任何地方都找不到初始化,因此只能假定它应该保持未定义状态(毕竟,您必须在某个地方定义它)。

相关问题