【问题标题】:Warning: Cannot update during an existing state transition警告:在现有状态转换期间无法更新
【发布时间】:2016-12-13 13:39:06
【问题描述】:

我有一个复杂的应用程序,它给了我以下警告:

警告:setState(...):在现有状态转换期间无法更新(例如在render 或其他组件的构造函数中)。渲染方法应该是 props 和 state 的纯函数;构造函数副作用是一种反模式,但可以移至componentWillMount

简而言之,当我按下“添加”按钮时会出现此警告,这应该会向我的应用程序添加另一个组件。下面是一段对应的代码:

<Button onClick={addChartHandler.bind(this)}><Glyphicon glyph="plus" /></Button>

addChartHandler 来自它的容器组件:

addChartHandler() {
    store.dispatch(addChart());
}

addChart 只是增加组件计数器。并且应用容器订阅了这些更改:

const mapStateToProps = (store) => {
    return {
        count: store.app.chartsCount
    };
}

我很难追踪警告,但每次渲染每个组件时我都会调用console.log。似乎在渲染这个组件(对于我的App 来说是哑组件)后会弹出这个警告:

render() {
    let charts = [];

    for (let i = 0; i < this.props.count; i++) {
        charts.push(<ChartContainer id={i} key={i} size={this.props.size} />);
    }
    console.log('APP RENDER');
    console.log(charts);
    return (
        <div className="container-padding">
            <NavContainer />
            {charts}
        </div>
    );
}

欢迎提出任何建议。已经为此工作了至少三个小时,没有任何想法。

【问题讨论】:

  • ChartContainer 在做什么?
  • @Christian 获取绘制图表所需的数据(使用chart.js)

标签: javascript reactjs redux react-redux


【解决方案1】:

这是代码行,因为代码导致了我觉得的问题:-

  for (let i = 0; i < this.props.count; i++) {
        charts.push(<ChartContainer id={i} key={i} size={this.props.size} />);
    }

我认为您在渲染中某处正在执行setState,或者您的状态正在更新它不应该执行的位置。可以分享一次ChartContainer 组件吗?

你可以试试这个吗?

constructor(){
   state : {
     charts : []
  } 
}

componentWillReceiveProps(nextProps){
  if(nextProps.count != this.props.count){
     let charts = []
     for (let i = 0; i < this.props.count; i++) {
        charts.push(<ChartContainer id={i} key={i} size={this.props.size}      />);
    }
   this.setState({charts:charts})
  }
}

render() {
    return (
        <div className="container-padding">
            <NavContainer />
            {this.state.charts}
        </div>
    );
}

【讨论】:

    【解决方案2】:

    这个解决方案帮助我理清思路。

    我遇到了这个错误,因为我在自己的构造函数中添加了this.setState({});

    所以我把它移到了componentWillReceiveProps,它成功了!

    谢谢@Harkirat Saluja

    【讨论】:

      【解决方案3】:

      感谢所有答案,我解决了这个问题:我在其他组件的constructor() 中调用了setState。对于那些正在寻找的人:仔细检查所有其他组件,以及它们的 render()constructor() 方法。

      【讨论】:

        猜你喜欢
        • 2017-12-20
        • 1970-01-01
        • 2017-05-16
        • 2016-09-20
        • 1970-01-01
        • 2016-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多