I want to pass a value.
It goes from Africa -> FetchContext -> Jumbotron. When it reaches Jumbotron it's undefined.
I think it's because Africa is never called again.
I send the value of the continent to a context. The idea is that this is a travel review site. All continents are ordered in a navbar. The Africa-component gets called whenever "Africa" in the navbar is clicked.
const Africa = ({}) => {
return (
<div>
<DataProvider continent={["Africa"]} />
This is the context:
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>
);
}
}
Wherever I console log this.props.continent, it's always the correct corresponding continent. However, as soon as I target a review, my jumbotron spawns, and here, the value is undefined.
This is my jumbotron:
const JumbotronPage = () => {
return (
<section className="page-section">
<DataProvider>
<DataContext.Consumer>
{(value) => (
<MDBContainer>
{console.log(value)}
I'm sure it's something stupid but I cannot figure it out. Thanks
TLDR; I pass prop to middle-component, setting the prop as state, sending the state as context to jumbotron-component. Here, the context is undefined.
Edit: SOLVED. I had to understand how to pass it to it's children.
JumbotronPage
has to be a child of DataProvider
.
In your case, this.props.children
is not used within 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>
);
};
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.