【问题标题】:Reordering index when mapping arrays with React使用 React 映射数组时重新排序索引
【发布时间】:2019-07-03 06:18:40
【问题描述】:

我正在更改映射中的对象属性,并且我想在对象属性为 changed ( = input disabled) 时更改索引,那么最好的方法是什么?

我已尝试为索引创建新数组,但无法使其工作,因为它需要一些具有单独数组的嵌套映射并且无法使其工作。

编辑:我在官方文档中使用索引来标记文本部分的位置,这就是为什么这个索引如此重要。

onToggleTextPart = (e, index) => {
    const node = this.myCheckbox[index]
    let newStates = [ ...this.state.meeting_parts ];
    if(node.checked) {
      newStates[index - 1].type_tag = "Included";
    }
    else {
      newStates[index - 1].type_tag = "notIncluded";
      newStates.splice(index-1, 1)

    }
    this.setState({ meeting_parts: newStates });
  }
return _.map(meeting_parts, (meet, index) => {
      let checked = meet.type_tag === "Included" ? true : false;
      return 
        <div className="form-group">
          <div className="input-group">
            <div className="input-group-prepend">
              <span className="input-group-text minutes-agenda-item-number">
                {index} (THIS is the index i want to change)
              </span>
            </div>

我想,即当我从索引 6 中隐藏一个对象时,它“放弃”它的索引,而索引 7 占据它的位置。

【问题讨论】:

  • 很难说出你真正想要达到的目标。您是否希望索引从 1 向上计数到 n,其中 n 是包含元素的数量?还有一个小提示:let checked = meet.type_tag === "Included" ? true : false;let checked = meet.type_tag === "Included" 相同

标签: javascript arrays reactjs object mapping


【解决方案1】:

好的,据我了解你想这样做:

meeting_parts.filter((meet)=>meet.type_tag === "Included").map((meet, index)=>{
 // your mapping function here
});

过滤器将返回 type_tag 为“包含”的会议数组。

您可以阅读filter function

编辑:

let includedCount = 0;
meeting_parts.map((meet, index)=>{
  if(meet.type_tag === "Included") {
    includedCount += 1;
  }
  // your mapping function here but use inlcudedCount instead of index
});

当然,现在它会多次显示一些数字。如果您不希望它们显示,则必须添加逻辑以在必要时禁用渲染。

【讨论】:

  • 天哪,是的!可能是,我试试这个:)
  • 几乎很好,但我希望其余部分仍然可见(此选项隐藏“nonIncluded”。它们是禁用的输入字段,但失去了“索引”位置。我一直在尝试切片数组和将它们移动到最后一个位置,但这会使映射变得如此糟糕..
  • 啊,我明白了。然后它不像我上面发布的那样工作。我将以我现在理解的方式更新我的操作。
  • {meet.type_tag === "Included" &amp;&amp; includedCount} 有了这个,它就可以完美地工作了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
相关资源
最近更新 更多