初始化之前无法导入上下文

时间:2019-12-20 18:44:59

标签: javascript reactjs react-context

我正在尝试从App.js的子组件中导入创建的上下文。

App.js

export const FilterContext = React.createContext("test");

export default class App extends React.Component {
    render() {
        return (
            <div className="App">
                <Navigation />
                <Hero />

                <FilterContext.Provider value="hello">
                    <OfferSorting />

                    <div className="wrapper">
                        <div className="container">
                            <Offer />
                        </div>
                    </div>

                    <NewOfferButton />
                </FilterContext.Provider>
            </div>
        );
    }
}

然后我要在<OfferSorting />中访问我的上下文

OfferSorting.js

import { FilterContext } from "../../../App";

export default class OfferSorting extends React.Component {
    static contextType = FilterContext;

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        console.log(this.context)
    }
}

但是在OfferSorting.js中,它将引发错误Cannot access 'FilterContext' before initialization。如何访问上下文,而不使用道具?

0 个答案:

没有答案