简体   繁体   中英

Setting State with setState() before Render?

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?

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 
}

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
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM