响应onClick的问题

时间:2017-06-28 18:37:39

标签: javascript reactjs giphy

我的应用程序有一个应该渲染更多GIF的onClick。然而,它只做一次然后停止。此外,onClick删除页面上已有的所有GIF。谁知道我做错了什么?

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      results: [],
    };
  }

  componentDidMount() {
    this.searchGifs('kittens');
  }

  searchGifs = (searchQuery) => {
    fetch(`http://api.giphy.com/v1/gifs/search?q=${searchQuery}&limit=12&api_key=dc6zaTOxFJmzC`).then(data => data.json())
      .then(response => {
        this.setState({
          results: response.data,
        });
     });
  }



  searchMoreGifs = (offsetQuery) => {
    fetch(`http://api.giphy.com/v1/gifs/search?q=${offsetQuery}&limit=12&offset=${this.state.results.length}&api_key=dc6zaTOxFJmzC`).then(data => data.json())
      .then(response => {
        this.setState({
          results: response.data,
        });
     });
  }


  render() {
    return (
      <main className="app">
        <Header />
        <SearchForm startSearch={this.searchGifs} />
        <ResultList gifs={this.state.results} />
        <LoadMore gifs={this.state.results} searchMore={this.searchMoreGifs} />
      </main>
    );
  }
}

这是onClick:

   class LoadMore extends React.Component {
    render(props) {
        return(
            <button onClick={this.props.searchMore}>Load More</button>
        );
    }
}


export default LoadMore; 

1 个答案:

答案 0 :(得分:1)

每次调用this.state.results时,您都会完全覆盖之前的结果状态。您想要使用class App extends Component { constructor(props) { super(props); this.state = { results: [], // I also suggest moving the searchQuery to the state so it can be used in both the offset and the original search searchQuery: 'kittens' }; } componentDidMount() { this.searchGifs(this.state.searchQuery); } searchGifs = (searchQuery) => { fetch(`http://api.giphy.com/v1/gifs/search?q=${searchQuery}&limit=12&api_key=dc6zaTOxFJmzC`).then(data => data.json()) .then(response => { this.setState({ results: response.data, }); }); } searchMoreGifs = (offsetQuery) => { fetch(`http://api.giphy.com/v1/gifs/search?q=${offsetQuery}&limit=12&offset=${this.state.results.length}&api_key=dc6zaTOxFJmzC`).then(data => data.json()) .then(response => { this.setState({ // You were overwriting the old results with new data every time you ran this function results: this.state.results.concat(response.data), }); }); } render() { return ( <main className="app"> <Header /> <SearchForm startSearch={this.searchGifs} /> <ResultList gifs={this.state.results} /> {/* You also need to pass the offsetQuery to the LoadMore component so that the searchMore function can use it*/} <LoadMore searchMore={this.searchMoreGifs} offsetQuery={this.state.searchQuery} /> </main> ); } } class LoadMore extends React.Component { render(props) { const {offsetQuery, searchMore} = this.props return ( <button onClick={() => searchMore(offsetQuery)}>Load More</button> ); } } export default LoadMore; 中的数组并将其与新结果连接起来。

{{1}}