简体   繁体   English

构造函数中未定义的上下文 - 反应

[英]Context undefined in constructor - react

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

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

I need to pass context to super to be able to access it within the constructor.我需要将上下文传递给 super 以便能够在构造函数中访问它。

Passing of context to constructor is not there in their latest documentation -他们的最新文档中没有将上下文传递给构造函数-

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

but it is there in the legacy api documentation.但它存在于旧版 api 文档中。

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

Since passing context to super will be deprecated in versions 17 and above, what is a way to be able to accees context within passing it to super in constructor?由于将上下文传递给 super 将在 17 及更高版本中被弃用,有什么方法可以在将上下文传递给构造函数中的 super 时访问上下文?

Thanks!谢谢!

Since passing react context to super will soon be deprecated, you won't be able to use the context in constructor.由于将 react 上下文传递给 super 将很快被弃用,因此您将无法在构造函数中使用上下文。 Another point would be, I've seen functional component is more preferred way of creating components (this is highly discussion topic) I would recommend using functional component and then simply use useEffect or useContext hook if it makes sense in the overall situation.另一点是,我已经看到功能组件是创建组件的更优选方式(这是一个高度讨论的话题)我建议使用功能组件,然后如果它在整体情况下有意义,则只需使用useEffectuseContext挂钩。

You can follow the same approach in the class component as well for eg.您也可以在 class 组件中采用相同的方法,例如。 using react lifecycle method componentDidMount() since context will be available once component is mounted, this lifecycle method makes sense to use context and call the method getPrinterInfo() in it.使用 react 生命周期方法componentDidMount()因为一旦组件被挂载,上下文就可用,这个生命周期方法使用上下文并在其中调用方法getPrinterInfo()是有意义的。

If you are not planning to update the react to 17, you can use the code that you have written since it is working, but if you want to update the react in future and want to work with it follow the other approach.如果您不打算将 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM