首页 > 解决方案 > 如何解决“加载后发送操作,循环问题”

问题描述

我正在尝试从我的仪表板页面发送数据操作this.props.dataActions.addChild(this.props.user.children.data[0])

但我有一个循环问题。我不知道在这种情况下该怎么办。请在下面检查我的代码:

我试图添加加载,componentDidUpdate但没有帮助。

componentDidUpdate() {
    // 
    console.log(this.state.loading)
    if (this.props.user && this.props.user.children && this.props.user.children.data) {
      console.log('iiiii', this.props.user.children.data[0])
      this.props.dataActions.addChild(this.props.user.children.data[0])
      if (!this.state.loading) {
        this.setState({ selectedChildren: this.props.user.children.data[0] })
      }

    }
  }

请检查截图:

停止循环并this.props.dataActions.addChild仅发送一次的最佳方法是什么

https://ibb.co/rm18W1b

仪表板索引代码: https ://pastebin.com/5V2ceAHK

标签: reactjs

解决方案


不建议setState在 didUpdate 生命周期内使用。但是,如果您对生命周期方法别无选择,则必须非常小心设置状态的条件

componentDidUpdate() {
    // 
    console.log(this.state.loading)
    if (this.props.user && this.props.user.children && this.props.user.children.data) {
      console.log('iiiii', this.props.user.children.data[0])
      this.props.dataActions.addChild(this.props.user.children.data[0])
      if (
        !this.state.loading &&
        this.state.selectedChildren !== this.props.user.children.data[0] // see this line here ??
      ) {
        this.setState({ selectedChildren: this.props.user.children.data[0] })
      }

    }
  }

在上面的代码中,您应该检查 selectedChildren 是否还不是您所在州的内容

this.state.selectedChildren !== this.props.user.children.data[0] 

如果这selectedChildren是一个对象,您必须使用对象比较模块,无论是定制的还是来自供应商包的。有关对象相等性的更多信息,请参阅

编辑:在您的代码中

componentDidUpdate(prevProps) {
    //

    if (
      this.props.user && 
      this.props.user.children && 
      this.props.user.children.data &&
      checkIf_prevProps.child isNotEqualTo this.props.user.children.data[0]
    ) {
      console.log('iiiii', this.props.user.children.data[0])
      this.props.dataActions.addChild(this.props.user.children.data[0])
    }
  }

所以检查是否checkIf_prevProps.child isNotEqualTo this.props.user.children.data[0]. 或者简单地检查状态变量中的任何条目,这样您就知道状态已经更新了。但请记住,这是一种保护无限渲染的肮脏黑客行为。


推荐阅读