【问题标题】:Sorting a Props array of objects by date before passing to child在传递给子对象之前按日期对 Props 对象数组进行排序
【发布时间】:2019-08-31 11:10:26
【问题描述】:

我有一个组件,它接收称为句点的对象数组

[
{id: 4, endDate: "2018-06-30T10:00:00+10:00"}
,{id: 3, endDate: "2017-06-30T10:00:00+10:00"}
,{id: 5, endDate: "2017-06-30T10:00:00+10:00"}
]

这是从其父级传递下来的,后者通过 graphql 调用接收。 如何按日期降序对该道具进行排序并将其传递给子组件以使用。 我试过了

      const arr = [...this.props.periods];
      const a2 = arr.sort((a, b) => b.endDate.localeCompare(a.endDate));
this.props.periods = a2
.
.
.(child component)
<Dropdown options={this.props.periods} />

并收到此错误

TypeError:无法分配给对象“#”的只读属性“句点”

【问题讨论】:

  • 您收到此错误是因为props 是只读的并且您正在为其分配一个新值。简单的解决方案可以是将排序后的数组添加到状态,然后将该状态传递给孩子。
  • 父级是否也从 graphql 调用中接收它作为道具?

标签: javascript reactjs sorting graphql-js


【解决方案1】:

您不能从子组件更新道具,因为道具是只读的。

您可以在父组件中更新状态。

【讨论】:

    【解决方案2】:

    this.props 中的所有属性都是只读的,你应该使用 state

    const periods = [...this.props.periods].sort((a, b) => 
    b.endDate.localeCompare(a.endDate));
    
    this.setState({periods})
    
    <Dropdown options={this.state.periods} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2011-10-30
      • 2015-02-25
      • 2013-10-26
      相关资源
      最近更新 更多