【问题标题】:Context undefined in constructor - react构造函数中未定义的上下文 - 反应
【发布时间】:2021-06-30 20:05:10
【问题描述】:
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 时访问上下文?

谢谢!

【问题讨论】:

    标签: reactjs constructor legacy-code react-class-based-component


    【解决方案1】:

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

    您也可以在类组件中采用相同的方法,例如。使用 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
        }
    }
    

    【讨论】:

    • 感谢您的回复。说得通。将移动到功能组件或在 componentDidMount 或渲染中调用它。将避免将上下文传递给 super,因为这将成为 react 版本升级的障碍。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2019-05-24
    相关资源
    最近更新 更多