React:我想在一个函数中调用两个API

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

我是ReactJS的新手,实际上我正在进行分页。我正在通过API从服务器获取页面数据。我正在使用Loopback进行API集成。在这里,我在第一页上显示10个条目列表,当用户点击下一个它将显示10-20个条目并且第一页的条目将被跳过。它可以使用Loopback过滤器,我通过手动完成,但我无法实现它的应用程序。我通过此API显示第一页数据调用localhost:8001/parties?filter[limit]=${userId}它将只显示10个条目,但我想要当用户单击下一个时它将跳过前10个条目并包括接下来的10个条目。 API调用此localhost:8001/parties?filter[limit]=${userId}&&filter[skip]=${userId}。有人可以请帮助如何做到这一点。谢谢

        class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
javascript reactjs ecmascript-6 loopback
1个回答
0
投票

你的getData函数中有setState,你总是将数据作为一个空数组,在我看来你应该删除它的第二个原因,你需要利用的第二件事就是将新的response.data添加到你状态的数据中。我希望这是你在找。

 getData(){
    const {userId}=this.state;
    this.setState({
      //delete the next line, don't make it empty array
      //data:[],
      loading:true
    })
    axios.get(`http://localhost:8001/parties?filter[limit]=${userId}`)
    .then(response=>{
      console.log(response.data);
      //and here just you have to use spread like this
      let newData= this.state.data;
      if(newData.length>0){// to be sure data is not empty
      newData = [...newData, ...response.data];
      }else{
      newData = response.data;
      this.setState({
        data: newData,
        loading:false
      })
    })
  }
© www.soinside.com 2019 - 2024. All rights reserved.