首页 > 解决方案 > 在反应中使用 Onclick 事件更新 Axios Url

问题描述

我正在API使用axios

  constructor(props) {
    super(props);
    this.state = {
      url:[],
      title:'anime',
      limit:6,
    }
    this.more_button.bind(this)
  }

  componentDidMount() {

  //limit is on the end of the url
  const limit= this.state.limit

     axios.get(`http://api.giphy.com/v1/gifs/search?q=sth&api_key=MY_KEY&limit=` + limit)
      .then(res => {
        const url= res.data.data;
        this.setState({ url });
      })

  }

limit当我点击一个按钮时,我想改变;我这样做:

  more_button=()=>{

      this.setState((previousState) => {
        return { limit: previousState.limit + 6 };
    });

    this.componentDidMount();

  }

问题是我应该单击该按钮两次才能工作。

渲染部分:

  render(){
    return(
      <div className="container">
              <button
              onClick={this.more_button} >
              Give me More!
              </button>
  )
    }
}

标签: reactjs

解决方案


ComponentDidMount 是一个生命周期方法。不要手动调用这个函数,试试下面的代码。

componentDidMount() {
  //limit is on the end of the url
  this.apiCall();
  }

 apiCall() {
      const limit= this.state.limit
      axios.get(`http://api.giphy.com/v1/gifs/search?q=sth&api_key=MY_KEY&limit=` + limit)
      .then(res => {
        const url= res.data.data;
        this.setState({ url });
      })
 }


more_button = () => {

  this.setState((previousState) => {
    return { limit: previousState.limit + 6 };
});
this.apiCall();
}

更改您的渲染 onClick 方法,例如:

onClick={()=>this.more_button}

最后在构造函数中添加额外的行:

constructor(props) {
    super(props);
    this.state = {
      url:[],
      title:'anime',
      limit:6,
    }
     this.apiCall = this.apiCall.bind(this);
     this.more_button = this.more_button.bind(this);
  }

推荐阅读