【问题标题】:How to output an array index in fetched data in React如何在 React 中输出获取的数据中的数组索引
【发布时间】:2019-04-14 20:05:22
【问题描述】:

以下代码发出 API 请求并显示收到的所有索引,这是一个 JSON 响应。

我需要输出从服务器响应获得的单个数据数组索引,而不是呈现列表:

class Test extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      data: []
    }
  }
  //request to api
  loadData() {
    fetch('https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5')
      .then(response => response.json())
      .then(data => {
        this.setState({
          data: data
        })
      })
      .catch(err => console.error(this.props.url, err.toString()))
  }
  componentDidMount() {
    this.loadData()
  }
  render() {
    return (
      //conclusion data
      {
        this.state.data.map((item) => {
          return <div class = "mypanel" > currency: {
            item.ccy
          }
          exchange: {
            item.buy
          } < /div>
        })
      }
    )
    React.render(document.getElementById('mypanel'));
  }
}

export default Test;

【问题讨论】:

  • 你能说清楚一点,'输出从api获得的单个数据数组索引'是什么意思。你的意思是数据数组的长度吗?
  • 我的意思是输出某个数组索引而不是所有内容。

标签: javascript node.js reactjs


【解决方案1】:

我假设您想要显示与从服务器接收的项目列表中的特定索引相对应的项目。你可以这样做:

<div class = "mypanel" > 
currency: { this.state.data[index].ccy} exchange: {
            this.state.data[index].buy
          } < /div>

其中 'index' 是您要显示的索引值。

【讨论】:

    【解决方案2】:

    如果您只想根据某些条件显示某些项目,那么您可以使用数组中的过滤器功能并过滤您的项目,如下所示。

    this.state.data.filter(item=>{
       return item.buy=== "buy"?true:false;
    }).map((item) => {
              return <div class = "mypanel" > currency: {
                item.ccy
              }
              exchange: {
                item.buy
              } < /div>
    })
    

    如果您只想显示某些项目,那么您可以使用 for 循环或 forEach 并只获取所需的项目。您可以编写一个单独的函数并像下面一样调用。

    function ShowSome(noOfItemsToTake){
          const items = [];
          const data = this.state.data; 
          const noOfItems=  noOfItemsToTake< data.length?noOfItemsToTake:data.length; 
    
              for (let i=0; i<noOfItems;i++)
              {
                items.push(  
                  <div class = "mypanel" > currency: {
                    data[i].ccy
                  }
                  exchange: {
                    data[i].buy
                  } < /div>) 
              }
         return items;  
    }
    
    
    
    
    render() {
        //Showing first 5   
        return this.ShowSome(5);
     }
    

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 1970-01-01
      • 2020-06-20
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2017-03-17
      • 1970-01-01
      相关资源
      最近更新 更多