简体   繁体   中英

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.

Passing of context to constructor is not there in their latest documentation -

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

but it is there in the legacy api documentation.

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?

Thanks!

Since passing react context to super will soon be deprecated, you won't be able to use the context in constructor. 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.

You can follow the same approach in the class component as well for eg. 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.

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.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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