代码之家  ›  专栏  ›  技术社区  ›  OmniOwl

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

  •  0
  • OmniOwl  · 技术社区  · 6 年前

    是的,我知道以前有人问过这个问题,但事实上,按建议做对我不起作用。

    所以我有以下方法必须在运行render()方法(在父级中)之前运行,因为我需要为Google图表和一些复选框准备大量数据。

    正如您在下面看到的,这在调用的函数中被调用 parseTestData :

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

    我遗漏了很多信息,因为我不被允许分享那部分。所以我调用函数 分组数据 来自父构造函数:

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

    但是这样做告诉我:

    无法对尚未装入的组件调用SetState。

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

    componentWillMount() {
        this.parseTestData();
    }
    

    但事实上,这并没有决定国家。所有依赖父状态的子级现在都会得到未定义的属性。

    我该怎么办?

    2 回复  |  直到 6 年前
        1
  •  1
  •   pr0p    6 年前

    读了你的文章,我觉得你对自己的反应还很陌生。

    基本上,当状态发生变化时,只要比较它维护的虚拟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 
    }
    
        2
  •  1
  •   Mahesh More    6 年前

    是的,不能在构造函数内使用此.setState()方法。您可以直接为状态赋值,而不是使用它。请参见下面的示例代码。

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