繁体   English   中英

在渲染之前使用setState()设置状态?

[英]Setting State with setState() before Render?

是的,我知道之前曾有人问过这个问题,但实际上对我来说行不通。

因此,在运行render()方法(在父级中)之前,我必须运行以下方法,因为我需要为Google图表和某些CheckBox准备大量数据。

如您在下面看到的,这在名为parseTestData的函数中被parseTestData

this.setState({
    data: ...,
    levels: ...,
    ...
    ...
    },
});

我已经省略了很多信息,因为我实际上没有被允许分享这一部分。 因此,我从父级构造函数调用了函数parseTestData

constructor(props) {
    super(props);
    this.parseTestData();
}

但是这样做告诉我:

无法在尚未安装的组件上调用setState。

环顾四周,建议似乎是这样做:

componentWillMount() {
    this.parseTestData();
}

但这实际上并没有设置状态。 现在,所有依赖于父状态的子代都会获得未定义的道具。

我该怎么办?

阅读您的文章,我认为您是React的新手。

基本上,每当状态发生变化时,React都会比较其维护的虚拟DOM与DOM并将其呈现,以检查是否有任何视觉变化。

如果在构造函数中调用方法,它将检测视觉变化并尝试渲染,因此每次构造函数都将被调用。

如果您将道具从父级传递到子级,并且已同意父级的状态,请确保您具有默认状态。

所以来到你的问题:

父级

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

儿童

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 
}

是的,您不能在构造函数中使用this.setState()方法,而是可以直接为状态分配一个值。 请参见下面的示例代码。

constructor(props)
{
  super(props);
  this.state = {
      data:'',
      levels: 2
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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