[英]Undefined React context
我想传递一个值。
它来自非洲 -> FetchContext -> Jumbotron。 当它到达 Jumbotron 时,它是未定义的。
我认为这是因为非洲再也没有被召唤过。
我将大陆的价值发送到一个上下文中。 这个想法是,这是一个旅游评论网站。 所有大陆都在导航栏中排序。 每当单击导航栏中的“非洲”时,都会调用非洲组件。
const Africa = ({}) => {
return (
<div>
<DataProvider continent={["Africa"]} />
这是上下文:
const DataContext = React.createContext();
export default DataContext;
export class DataProvider extends Component {
constructor(props) {
super(props);
console.log("Props " + this.props.continent + " in fetchcontext.js");
this.state = {
title: '',
};
}
updateState() {
this.setState({
title: this.props.continent,
});
}
componentDidMount() {
console.log("Comp did mount: " + this.props.continent)
}
componentWillUnmount() {
console.log("Comp did unmount: " + this.props.continent)
}
render() {
return (
<DataContext.Provider value={{ value: this.props.continent }}>
{this.props.children}
</DataContext.Provider>
);
}
}
无论我在哪里控制台记录 this.props.continent,它始终是正确的对应大陆。 但是,一旦我针对评论,我的 jumbotron 就会产生,而这里的值是未定义的。
这是我的大屏幕:
const JumbotronPage = () => {
return (
<section className="page-section">
<DataProvider>
<DataContext.Consumer>
{(value) => (
<MDBContainer>
{console.log(value)}
我确定这很愚蠢,但我无法弄清楚。 谢谢
TLDR; 我将 prop 传递给中间组件,将 prop 设置为 state,将 state 作为上下文发送给 jumbotron-component。 在这里,上下文是未定义的。
编辑:已解决。 我必须了解如何将它传递给它的孩子。
JumbotronPage
必须是DataProvider
的子级。
在您的情况下, this.props.children
未在DataProvider
中使用。
const DataContext = React.createContext();
const JumbotronPage = () => {
// ["Africa"]
return (
<DataContext.Consumer>
{value => {
console.log(value);
}}
</DataContext.Consumer>
);
};
class DataProvider extends React.Component {
render() {
return (
<DataContext.Provider value={this.props.continent}>
{this.props.children}
</DataContext.Provider>
);
}
}
const App = () => {
return (
<DataProvider continent={['Africa']}>
<JumbotronPage />
</DataProvider>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.