【问题标题】:React context (this.context) is undefined at constructor call timeReact 上下文(this.context)在构造函数调用时未定义
【发布时间】:2021-04-20 21:06:38
【问题描述】:

我正在尝试编写一个使用来自this.context 的值来派生状态对象的类组件。我有一个方法getStyle 可以返回这样一个对象。在constructor 时间,我正在调用this.getStyle 以从已经是最新的状态开始,并加快初始渲染速度。

但是,在constructor 通话时间,this.context 似乎是undefined,并且在render 通话时间之前一直如此。

我的代码有问题吗?

我不记得在 React 的(新)上下文 API 文档中与此类问题相关的任何细节。 this.contextcomponentDidMount 时间可用,但是,这需要setState,这将导致我想避免的额外组件重新渲染。

下面是我尝试使用的代码:

import React from "react";
import { View, Text } from "react-native";


const defaultTheme = {
    light: { backgroundColor: "white" },
    dark: { backgroundColor: "black" }
};

const customTheme = {
    light: { backgroundColor: "#EEE" },
    dark: { backgroundColor: "#111" },
};

const MyContext = React.createContext(defaultTheme);


class Container extends React.PureComponent {
    static contextType = MyContext;

    constructor(props) {
        super(props);

        this.state = this.getStyle();   // TypeError: undefined is not an object (evaluating '_this.context[_this.props.colorScheme || "light"]')
        // this.state = {}; // use this to try the componentDidMount alternative
    }

    componentDidMount = () => {
        const style = this.getStyle();
        this.setState(style);
    }

    getStyle = () => {
        // this.props.colorScheme = "light" | "dark" | null | undefined
        return this.context[this.props.colorScheme || "light"];
    }

    componentDidUpdate = (prevProps, prevState, snapshot) => {
        if (prevProps.colorScheme !== this.props.colorScheme) {
            const style = this.getStyle();
            this.setState(style);
        }
    }

    render = () => {
        return <View style={this.state}>
            {this.props.children}
        </View>;
    }
}


export default function App() {
    return <MyContext.Provider value={customTheme}>
        <Container>
            <Text>Hello, world!</Text>
        </Container>
    </MyContext.Provider>
}

【问题讨论】:

  • 我认为这是一个过早的优化。组件安装后的单个额外渲染可能不会对性能产生太大影响。我认为这里的困难更多在于您将如何使用上下文更新 colorScheme 和/或主题(来自与 App 不同的组件)。
  • 是的,一次重新渲染可能不会影响单个组件,但我正在制作一些通用组件,这些组件可能会嵌套在许多层次深处。我已经尝试过了,它在初始渲染时会出现小幅下降,类似于闪烁。如果我可以一开始就准备好,那将完全消除这个问题。

标签: reactjs undefined react-context


【解决方案1】:

尝试将上下文传递给构造函数:

constructor(props, context) {
    // your code here
}

根据this,此解决方案可能已被弃用,但您可以尝试。

【讨论】:

  • 自从 React 16 中的新 Context API 以来,该语法已被弃用。我认为 React 17 完全删除了对它的支持。但是,我找到了另一个可用的解决方案,我稍后会发布答案。
猜你喜欢
  • 2015-11-29
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
相关资源
最近更新 更多