【问题标题】:Error: Maximum update depth exceeded. React state错误:超过最大更新深度。反应状态
【发布时间】:2021-03-31 06:25:29
【问题描述】:

我猜我收到这个错误是因为反应的状态爆发了,但我不知道这里出了什么问题。

所以我有父子关系组件,如下所示:

父组件

class App extends Component {
    constructor(props){
        super(props);
        this.state={
            parentTime: 0,
        }
    };
    
    
    changeTimeState(childTime){
        //this.setState({parentTime: childTime})
        console.log("Parent state time: ",childTime)
    }
    render() {
        return (
            <div className="box">
                <Child time={this.state.parentTime} changeTime={this.changeTimeState.bind(this)}/>
            </div>
        );
    }
}

儿童组件

class Child extends Component {
    constructor(props){
        super(props)
        this.state = {
            childTime: props.time
        }
    }

    componentDidMount(){
            if (this.state){
                setInterval(()=>{
                    this.setState({childTime: this.state.childTime+1})
                },1000)
            }
        }
    
    render() {
        return (
            <div newTime={this.props.changeTime(this.state.childTime)}/>
        );
    }
}

我在它们之间传递数据并在父组件中取消注释 this.setState({parentTime: childTime}) 会导致该错误。这是我需要帮助来理解和修复它的地方。

【问题讨论】:

  • 这是因为你调用了一个函数,在将它作为某种道具传递给 div 时直接改变状态:
    ...不应该这样调用改变状态的函数。它应该只在用户交互时或在特定时间间隔调用。你想用这个做什么?
  • 为了更好地解释发生了什么......当你调用这样的函数时,父组件的状态会改变,所以它会重新渲染......同时它也会重新渲染子组件,这将再次调用该函数来改变父组件的状态......这将重新渲染---所以我们有一个无限循环
  • 你想让你的组件在这里做什么?
  • 你好@OliverRadini 我希望我的计时器在后台运行,我为此使用子组件,因为如果我在父组件中设置componentDidMount(),那么它也会重新渲染所有其他组件,这就是我尝试的原因制作单独的组件来克服这一点。 (不知道有没有其他办法)
  • 嗨@TalmacelMarianSilviu 感谢您抽出宝贵的时间。我的计时器在后台运行,因此无法进行用户交互。如何在特定的时间间隔内完成?

标签: javascript reactjs


【解决方案1】:
i don't know is it what you wanted 

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      childTime: props.time,
    };
  }

  componentDidMount() {
    if (this.state) {
      setInterval(() => {
        this.setState({ childTime: this.state.childTime + 1 });
        this.props.changeTime(this.state.childTime);
      }, 1000);
    }
  }

  render() {
    return <div />;
  }
}

【讨论】:

  • 你好@BogdanPryvalov,是的,这正是我想要的。但是当我使用函数changeTime() 将其设置为父状态时,它给了我undefined
  • 还有什么方法可以让我在状态更新时不必重新渲染所有其他组件,但我的计时器应该始终在后台运行?
  • 我只是不明白为什么你需要在 child comp 中声明它应该计算什么以及 childTime 和 parentTime 之间的区别到底是什么?
  • 是的,你是对的。实际上,我在从完整的长代码中取出特定代码时忘记更改它
猜你喜欢
相关资源
最近更新 更多
热门标签