Reputation: 125
I'm trying to make my context work properly. I've added it and it works as it should if I pass a string as a property to the state. However, I want to pass a prop as the state.
So this works:
export class DataProvider extends Component {
constructor(props) {
super(props);
this.state = {
continent: props.continent,
};
this.updateState = this.updateState.bind(this);
}
updateState() {
this.setState({ continent: this.props.continent});
}
componentDidMount() {
console.log(this.props.continent);
this.updateState();
}
render() {
return (
<DataContext.Provider value={{ state: this.state }}>
{this.props.children}
</DataContext.Provider>
);
}
}
But this does not work (results in undefined)
this.state = {
continent: this.props.continent,
};
Results in "undefined" when I try to access it.
I get the prop from a component named "Africa", which does this:
const Africa = ({}) => {
return (
<div>
<DataProvider continent={["Africa"]} />
........irrelevant code
It successfully passes to my DataProvider component. But, as I stated, when I try to pass that as a property for my state, it results in "undefined".
class JumbotronPage extends Component {
static contextType = DataContext;
render() {
console.log(this.context)
A(DataProvider), B(Africa), C(JumbotronPage) I'm not sure if it's because A and B recognizes each other. B and C does not.
So whenever I access C from A, B gets re-rendered, resulting in giving C nothing as state. Does that make sense?
Please, forgive me for being very green and new to React. I hope I make some sense.
Thanks
Edit: setState did not seem to work properly. I threw it into a componentDidMount, I can now set string-states, however, as soon as I pass my props to it, it's undefined.
Edit2: This is part of my App.js:
<Route exact path="/Login" component={Login} />
<Route exact path="/Jumbotron">
<DataProvider>
<JumbotronPage />
</DataProvider>
</Route>
<Route exact path="/CreateNewMemories" component={renderForm} />
Edit3: I created a gist, if someone has the time an patience to have a look at my abomination.
https://gist.github.com/kalleftw/e79412034eafd29a2e26b1af24149e67
Edi4: Do I even need to set the state?
this.state = {
continent: props.continent,
};
This seems to work when I log it with componentDidMount. However, as soon as I try to access the component "Jumbotron", the context there is undefined.
Upvotes: 0
Views: 92
Reputation: 3501
The correct way to update the state is with setState
, right, but it is a function. Use this.setState({ ... })
not this.setState = { ... }
Upvotes: 1