如何获取新数组onClick?

时间:2019-03-17 23:21:30

标签: reactjs

constructor() {
  super();

  this.state = {
    meme: {},
    num: 6
  };
  this.APIURL = `http://meme.com/${this.state.num}`;
}

componentDidMount() {
  fetch(this.APIURL)
    .then(resp => resp.json())
    .then(data => {
      console.log(data);
      if (data) {
        this.setState({
          meme: data
        });
      }

      console.log(this.state.meme);
    });
}

nextPic = () => {
  if (this.state.num > this.state.meme.totalMemes) {
    this.setState({
      num: 1
    });
  } else {
    this.setState({
      num: this.state.num + 1
    });
    console.log(this.state.num);
  }
};

render() {
  return (
    <div>
      <h1>{this.state.meme.title}</h1>
      <img key={this.state.num} src={this.state.meme.encodedurl} />
      <button onClick={this.nextPic}>Next</button>
    </div>
  );
}

这取决于this.state.num调用api。我该如何做,以便在调用nextPic()时调用this.state.num + 1?现在,this.state.num得到更新,但不会再次获取api。

API的外观如下:

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以将提取操作移到一个单独的方法中,您可以同时在componentDidMountnextPic中调用该方法。

示例

class App extends React.Component {
  state = {
    meme: {},
    num: 6
  };

  componentDidMount() {
    this.fetchMeme();
  }

  fetchMeme = () => {
    const url = `http://meme.com/${this.state.num}`;

    fetch(url)
      .then(resp => resp.json())
      .then(data => {
        this.setState({
          meme: data
        });
      });
  };

  nextPic = () => {
    this.setState({
      num: this.state.num >= this.state.meme.totalMemes ? 1 : this.state.num + 1
    }, this.fetchMeme);
  };

  render() {
    return (
      <div>
        <h1>{this.state.meme.title}</h1>
        <img key={this.state.num} src={this.state.meme.encodedurl} />
        <button onClick={this.nextPic}>Next</button>
      </div>
    );
  }
}

答案 1 :(得分:0)

使api提取调用函数。试试这个:

constructor() {
  super();

  this.state = {
    meme: {},
    num: 6
  };

}

componentDidMount() {
  fetchFromAPI(this.state.num);
}

let fetchFromAPI = (num)=>{

this.APIURL = `http://meme.com/${num}`;

   fetch(this.APIURL)
    .then(resp => resp.json())
    .then(data => {
      console.log(data);
      if (data) {
        this.setState({
          meme: data
        });
      }

      console.log(this.state.meme);
    });

}

nextPic = () => {
  if (this.state.num > this.state.meme.totalMemes) {
    this.setState({
      num: 1
    });
  } else {
    this.setState({
      num: this.state.num + 1
    });
    console.log(this.state.num);
  }
   fetchFromAPI(this.state.num);
};

render() {
  return (
    <div>
      <h1>{this.state.meme.title}</h1>
      <img key={this.state.num} src={this.state.meme.encodedurl} />
      <button onClick={this.nextPic}>Next</button>
    </div>
  );
}

我没有对此进行测试,但是看起来它可以工作。