TypeScript + React:避免在未安装的组件上使用setState

问题描述 投票:0回答:1

[我知道避免在未安装的组件上调用.setState()的常见模式是通过添加诸如_isMounted的私有属性来跟踪它,如blog中所述。

我一直在使用这种方法:

class Hello extends React.PureComponent{
_isMounted = false;

constructor(props) {
    super(props);
    this.state = {
        // ...
    };
}

componentDidMount() {
    this._isMounted = true;
}

componentWillUnmount() {
    this._isMounted = false;
}
// ...
}

在我开始使用TypeScript之前,一切都很好。我尝试以相同的方式执行此操作:

class Hello extends React.PureComponent<Props, State> {
private _isMounted: boolean;

constructor(props: Props) {
    super(props);
    this.state = {
        // ...
    };
}

componentDidMount() {
    this._isMounted = true;
}

componentWillUnmount() {
    this._isMounted = false;
}
}

但是它总是会引发类型错误:

TypeError: Cannot set property _isMounted of #<Component> which has only a getter

就目前而言,我知道的唯一解决方案是为其显式编写一个setter。但是我真的不明白这是否是预期的方法。 TypeScript不会自动生成getter和setter吗?

更新:代码框示例:https://codesandbox.io/s/l59wnqy5zz

reactjs typescript
1个回答
0
投票

对其他开发人员可能有用使用获取器和设置器

class Hello extends React.Component {
    private isFullyMounted: boolean = false;

    public componentDidMount() {
        this.isMounted = true;
    }

    public componentWillUnmount() {
        this.isMounted = false;
    }

    public set isMounted(status: boolean) {
        this.isFullyMounted = status;
    }

    public get isMounted() {
        return this.isFullyMounted;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.