【问题标题】:react component state does not reset on subsequent call for same component反应组件状态不会在后续调用相同组件时重置
【发布时间】:2018-08-07 18:27:24
【问题描述】:

所以我的组件看起来像下面提到的这样。 当组件第一次渲染时,它会设置状态。但是对于第二次调用,道具保存新数据但它从未设置状态。相反,状态具有以前的数据。不确定是什么导致了这种行为。我感兴趣的状态是“数据”

class MuiTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      order: 'asc',
      orderBy: this.props.columnData[0].id,
      selected: this.props.defaultAllSelect !== undefined && this.props.defaultAllSelect ? this.props.data.map(d=> d[this.props.uniqueKey]) : [],
      data: this.props.isSortable ? this.props.data.sort((a, b) => (a[this.props.columnData[0].id] < b[this.props.columnData[0].id] ? -1 : 1)) : this.props.data,
      page: 0,
      rowsPerPage: this.props.rowsPerPage,
      uniqueKey: this.props.uniqueKey
    };
  }
}

【问题讨论】:

    标签: node.js reactjs refluxjs


    【解决方案1】:

    请尝试实现 componentWillReceivedProps(nextProps) 方法并使用 this.setState();更新您的状态。

    这可能会对您有所帮助:React lifecycle

    【讨论】:

    • 嗨,Kevin,感谢您在这里指导我。这个解决方案确实有帮助,我的组件现在可以工作了。
    【解决方案2】:

    这是正常的,因为这是构造方法。
    您应该阅读组件生命周期方法,doc

    对于生命周期的更新部分,它是:

    1. componentWillReceiveProps()
    2. shouldComponentUpdate()
    3. componentWillUpdate()
    4. 渲染()
    5. componentDidUpdate()

    【讨论】:

    • 谢谢!有时这完全是因为不了解基础知识。
    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多