【问题标题】:Why isn't my React child component receiving new props?为什么我的 React 子组件没有收到新的道具?
【发布时间】:2017-10-03 15:25:48
【问题描述】:

我有一个作为可排序表的 React 组件。表头和表行是容器的子项,容器正在处理表的状态。单击标题时,数据会重新排序,就像在 this semantic-ui-react example 中一样。

handleSort = (clickedColumn) => {
const { column, orders, direction } = this.state

if (column !== clickedColumn) {
  this.setState({
    column: clickedColumn,
    orders: customSort(orders, clickedColumn),
    direction: 'ascending',
  })
} else {
this.setState({
  orders: orders.reverse(),
  direction: direction === 'ascending' ? 'descending' : 'ascending',
})}

第一次单击列标题时,第一个闭包运行,this.setState 更改容器的状态,并触发子项接收新的道具并相应地更新。如果我重新单击列标题以反转数据的顺序,第二个闭包运行,this.setState 更新容器的状态。因此,子组件OverviewTableHeader 会更新,但OverviewTableRows 不会。

render() {
const { designers, orders, column, direction } = this.state
if (orders === "loading"){
  return <Loading />
} 
const tableRows = <OverviewTableRows  
                     designers={designers} 
                     orders={this.state.orders}
                     />
debugger
return (
  <div className="overview">
    <Table selectable fixed sortable>
      <OverviewTableHeader sort={this.handleSort} column={column} direction={direction}/>
      {tableRows}
    </Table>
  </div>
  ) 
}

Here's a video of this in action.

在视频中,您可以看到OverviewTableRows 触发componentWillReceivePropsshouldComponentUpdate 第一次在父级中触发setState,但不是第二次。

如果需要,我可以添加我的所有代码。这是一个错误吗?非常感谢任何帮助!

【问题讨论】:

    标签: reactjs setstate react-lifecycle


    【解决方案1】:

    我通过在反转数组之前复制数组并使用它来更新状态来解决这个问题。

    handleSort = (clickedColumn) => {
    const { column, orders, direction } = this.state
    
    if (column !== clickedColumn) {
      this.setState({
        column: clickedColumn,
        orders: customSort(orders, clickedColumn),
        direction: 'ascending',
      })
    } else {
      const reversedOrders = orders.slice().reverse();
    this.setState({
      orders: reversedOrders,
      direction: direction === 'ascending' ? 'descending' : 'ascending',
    })}
    

    我猜orders 数组的身份很重要。我猜这与 React 的功能特性有关。我希望这对某人有帮助!如果有人能很好地解释为什么会这样,我很想听听。

    【讨论】:

      【解决方案2】:

      这是一个很好的报价,可以解释发生了什么。

      通过直接操作 this.state,你绕过了 React 的状态管理,这可能是危险的,因为之后调用 setState() 可能会替换你所做的突变。

      取自this article

      由于orders 是一个可变对象并且是state 的成员,因此当您调用orders.reverse 时,您正在直接更改状态(即使此重新排序是在setState 调用中完成的)。

      所以,是的,您创建 orders 副本的解决方案将解决此问题,因为您不再直接更改 this.state

      【讨论】:

        猜你喜欢
        • 2018-06-03
        • 2015-04-25
        • 1970-01-01
        • 2021-03-25
        • 2021-11-10
        • 1970-01-01
        • 2019-04-29
        • 2018-11-25
        • 2018-05-08
        相关资源
        最近更新 更多