【问题标题】:How can I set a specific position to array elements with the map function and a given index?如何使用 map 函数和给定索引为数组元素设置特定位置?
【发布时间】:2018-02-04 16:05:01
【问题描述】:

我正在使用一个显示来自服务器的动态数据的反应站点。这是来自父母的内容。

  axiosFunc = () => {

  axios.get('https://api.warframestat.us/pc').then(results => {
  this.setState({
    fissures: results.data.fissures
  });

  console.log(this.state.fissures)

      setTimeout(this.axiosFunc,1000 * 60);
    })
  }

  componentDidMount() {
    this.axiosFunc();
  }

现在当我在子元素中使用map函数时,弹出数据...

  render() {
return(
  <main>
    <header>{this.props.whichEvent.toUpperCase()}</header>
    {
      this.props.theData.map(
        fissure => {
          return (
            <section key={fissure.id}>
              <h1>{fissure.missionType} // {fissure.node}</h1>
              <figure className="leftfigure">
                <img src={require(`../icons/${fissure.tier}.svg`)} alt=""/>
                <figcaption></figcaption>
              </figure>
              <figure>
                <figcaption></figcaption>
              </figure>
            </section>
          )
        }
      )
    }
  </main>
)
}

但无论服务器将对象传递给我的顺序如何,它都会出现。我想根据每个对象中的 fissure.tierNum 值对它们进行排序。根据对象,数字从 1 到 4。当我使用 map 制作元素时,如何获取该数字并根据它对元素进行排序?

【问题讨论】:

    标签: javascript arrays reactjs sorting


    【解决方案1】:

    只需在您的地图功能之前添加排序功能即可按您想要的键排序

    this.props.theData.sort((a,b) => {
      if(a.tierNum < b.tierNum) {
        return -1;
      }
      else return 1;
    }).map(...)
    

    您可以在MDN docs了解更多关于排序功能的信息

    【讨论】:

    • 谢谢。主要问题是我不知道如何在这里设置排序功能,因为我从来没有同时排序和映射。
    猜你喜欢
    • 2012-01-12
    • 1970-01-01
    • 2019-06-23
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多