Reputation: 5709
Yes I know the question has been asked before, but actually doing what is suggested doesn't work for me.
So I have the following method that has to run before I run my render() method (in the parent), because I need to prepare a lot of data for a Google Chart and some CheckBoxes.
As you can see below, this gets called in the function called parseTestData
:
this.setState({
data: ...,
levels: ...,
...
...
},
});
I've omitted quite some information, because I'm not really allowed to share that part. So I call the function parseTestData
from the parents constructor:
constructor(props) {
super(props);
this.parseTestData();
}
But doing so tells me this:
Can't call setState on a component that is not yet mounted.
Looking around, the suggestion seems to be to do this instead:
componentWillMount() {
this.parseTestData();
}
But that doesn't actually set the state at all. All of the children that relies on the parent state now gets undefined props.
What should I do?
Upvotes: 1
Views: 4975
Reputation: 855
Yes, you can't use this.setState() method inside constructor.Instead of it, you can directly assign a value to the state. Please see below sample code.
constructor(props)
{
super(props);
this.state = {
data:'',
levels: 2
}
}
Upvotes: 1
Reputation: 2358
Reading your post i think you are quite new to React.
Basically React checks for any visual changes whenever state changes comparing Virtual DOM it maintains with the DOM and renders it.
If you call your method in the constructor, it will detect visual changes and tries rendering so each time the constructor will be called.
If you are passing props from parent to child make and it is connented to the state of the parent make sure you have a default state.
So coming to your question :
Parent
constructor(props){
super(props)
this.state = // set your state but don't ever change state here
.....
}
componentDidMount(){
this.parseTestData(); // componentWillMount will also work fine
}
render(){
return(
<Child arg={this.state.someArg} />
)
}
Child
constructor(props){
super(props)
this.state = // set your state but don't ever change state here
.....
}
anyFunction(){
console.log(this.props.arg) // You can access your arguments here
}
Upvotes: 2