【问题标题】:Root element ID differed from reactRootID根元素 ID 与 reactRootID 不同
【发布时间】:2015-10-10 07:09:31
【问题描述】:

有一个 react.js 组件,它在 componentDidMount 方法内进行三个 ajax 调用,并根据每个调用的结果设置状态。当我“链接”调用以便它们以特定顺序执行时,出现标题中的错误。如果我在没有链接的情况下执行此操作,则不会出现错误,但这不会 100% 起作用,因为不能保证 A 会在 B 之前完成,B 会在 C 之前完成。

为什么 react 抱怨根元素 ID?

componentDidMount() {
    var self = this;

    // this doesn't produce the error but is not acceptable
    $.ajax({.. A ..}).done(function(result) { self.setState({a: result}); });
    $.ajax({.. B ..}).done(function(result) { self.setState({b: result}); });
    $.ajax({.. C ..}).done(function(result) { self.setState({c: result}); });

    // chaining doesn't work
    //self.getA();
    // Root element ID differed from reactRootID
}

getA() {
    var self = this;
    $.ajax({...})
        .done(function(result) { self.setState({a: result}); self.getB(); });
}

getB() {
    var self = this;
    $.ajax({...})
        .done(function(result) { self.setState({b: result}); self.getC(); });
}

getC() {
    var self = this;
    $.ajax({...})
        .done(function(result) { self.setState({c: result}); });
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    可能是因为 react 不喜欢在 componentDidMount 中链接多个 setState()。

    更好的设置:

    • 从 componentDidMount 调用 getA。
    • 在状态中包含 gotTo: 'A'
    • 在 componentDidUpdate 中:调用 getB(如果 this.state.gotTo == 'A')否则调用 getC

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多