0
export default class Printer extends React.PureComponent<PrinterProps> {
    static contextType = PrinterContext;

    constructor(props: PrinterProps, context: PrinterInterface){
        super(props, context);
        this.PrinterInfo = getPrinterInfo(this.context);
}

我需要将上下文传递给 super 以便能够在构造函数中访问它。

他们的最新文档中没有将上下文传递给构造函数-

https://reactjs.org/docs/context.html

但它存在于旧版 api 文档中。

https://reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods

由于将上下文传递给 super 将在 17 及更高版本中被弃用,有什么方法可以在将上下文传递给构造函数中的 super 时访问上下文?

谢谢!

4

1 回答 1

0

由于将 react 上下文传递给 super 将很快被弃用,因此您将无法在构造函数中使用上下文。另一点是,我已经看到功能组件是创建组件的更优选方式(这是一个高度讨论的话题),我建议使用功能组件,然后在整体情况下简单地使用useEffect或挂钩。useContext

您也可以在类组件中遵循相同的方法,例如。使用 react 生命周期方法componentDidMount(),因为一旦安装组件,上下文将可用,此生命周期方法使用上下文并调用其中的方法是有意义的getPrinterInfo()

如果您不打算将 react 更新到 17,则可以使用您编写的代码,因为它正在工作,但如果您想在将来更新 react 并希望使用它,请遵循其他方法。

export default class Printer extends React.PureComponent<PrinterProps, State> {
    static contextType = PrinterContext;
    context!: React.ContextType<typeof PrinterContext>;

    constructor(props: PrinterProps){
        super(props);
    }

    componentDidMount() {
        this.getPrinterInfo();
    }

    getPrinterInfo = () => {
        // you should have access to this.context
    }
}
于 2021-04-04T19:53:43.923 回答