如何从获取请求中获取响应的长度?

问题描述 投票:0回答:2

我有一系列数据包含一个数组(json文件)中的一些对象,它将通过react显示。这是我的代码:

 class App extends React.Component {
      constructor(props){
        super(props);
        this.state = {
        data: [],
        library:null,
        perPage: 20,
        currentPage: 1,
        maxPage: null,
        filter: ""
        };
       }
   componentDidMount() {
   fetch('/json.bc')
  // Here I want to get the length of my respose 
  .then(response => response.text())
  .then(text => {
  var Maindata = JSON.parse(text.replace(/\'/g, '"'))
   this.setState(state => ({
   ...state,
   data: Maindata
     }), () => {
     this.reorganiseLibrary()
    })
   }).catch(error => console.error(error))
}
  reorganiseLibrary = () => {
  const { filter, perPage , data } = this.state;
  let library = data;
    if (filter !== "") {
      library = library.filter(item =>
      item.hotelinfo.hotelsearch.realname.toLowerCase().includes(filter)
   );
 }

 library = _.chunk(library, perPage);
   this.setState({
   library,
   currentPage: 1,
   maxPage: library.length === 0 ? 1 : library.length
 });
};
// Previous Page
  previousPage = () => 
  this.setState(prevState => ({
  currentPage: prevState.currentPage - 1
}));
// Next Page
  nextPage = () =>
   this.setState(prevState => ({
    currentPage: prevState.currentPage + 1
  }));

// handle filter
  handleFilter = evt =>
   this.setState(
     {
     filter: evt.target.value.toLowerCase()
   },
   () => {
     this.reorganiseLibrary();
   }
  );
 // handle per page
  handlePerPage = (evt) =>
   this.setState({
   perPage: evt.target.value 
}, () => this.reorganiseLibrary());

 // handle render of library
     renderLibrary = () => {
      const { library, currentPage } = this.state;
       if (!library || (library && library.length === 0)) {
        return <div class="tltnodata">no result!</div>;
    }
    return library[currentPage - 1].map((item, i) => (
       <input type="hidden" value={item.hotelinfo.hotelsearch.hotelid} name="hotelid"/>
   ));
 };

render() {
const { library, currentPage, perPage, maxPage } = this.state;
return (
  <div className="Main-wrapper">
    <div class="filter_hotelname"><input value={this.state.filter} onChange={this.handleFilter} class="hotelName" /></div>
      <div class="countHotel"> <span class="numbersearch"></span> // Here I want two show the count of items </div>
      <div className="wrapper-data">
          {this.renderLibrary()}
      </div>
      <div id="page-numbers">
          <div class="nexprev">
            {currentPage !== 1 && (
              <button onClick={this.previousPage}><span class="fa-backward"></span></button>
            )}
          </div>
          <div className="data_page-info">
          {this.state.currentPage} از {this.state.maxPage}
      </div>
          <div class="nexprev">
            {(currentPage < maxPage) && (
              <button onClick={this.nextPage}><span class="fa-forward"></span></button>
            )}
          </div>

      </div>

  </div>
    );
   }         
  }
 ReactDOM.render(<App/>, document.getElementById('Result')); 

我想找一个带有fetch的请求的响应长度。另外,我想知道如何找到renderLibrary将显示的项目数。例如,在json.bc中,我们有4个对象,我想在数字范围内显示4个。

json reactjs
2个回答
0
投票

使用Fetch API,您可以通过运行下面的代码片段找到json响应项长度。我也在代码中添加了注释。

fetch('https://jsonplaceholder.typicode.com/todos')
    .then(response => {
        //below method return promise based response by converting stream object to json
        return response.json();
    }).then(json => {
        //Once succcessful callback return you can find length of number of item
        console.log(json);
        alert("Number of item:"+json.length)
    })
fetch('https://jsonplaceholder.typicode.com/todos')
    .then(response => {
        //below method return promise based response by converting stream object to json
        return response.json();
    }).then(json => {
        //Once succcessful callback return you can find length of number of item
        alert(json.length)
    })

0
投票

您可以使用状态数据数组的长度来区分项目数。

由于数组从0开始,您需要将计数递增1。下面是您可以在代码示例中使用的示例代码段。

<div class="countHotel"><span class="numbersearch">{this.state.data && this.state.data.length + 1}</span></div>
© www.soinside.com 2019 - 2024. All rights reserved.