代码之家  ›  专栏  ›  技术社区  ›  Biii

React中的搜索功能和获取api

  •  3
  • Biii  · 技术社区  · 6 年前

    我正在开发一个调用Unsplash的API并显示响应的应用程序。我只需使用 /photos 当我在 componentDidMount() ,但我想让应用程序可以搜索,所以我添加了 performSearch() 使用默认查询。

    但正在添加 performSearch 导致此错误的原因: TypeError: cannot read property 'map' of undefined

    这是我测试时得到的JSON: Search endpoint + query

    我尝试了在论坛上找到的其他解决方案,但到目前为止,没有任何解决方案。我肯定会得到一个数组,所以不应该 map 工作

    class App extends Component {
    
      constructor() {
        super();
        this.state = {
          results: [],
          loading: true
        };
      }
    
      componentDidMount() {
        this.performSearch();
      }
    
      performSearch = (query = 'camping') => {
        fetch(`https://api.unsplash.com/search/photos?page=3&query=${query}&client_id=${client_id}`)
          .then(response => response.json())
          .then(responseData => {
            this.setState({
              results: responseData.data,
              loading: false
            });
          })
          .catch(error => {
            console.log('Error fetching and parsing data', error);
          });
      }
    
      render() {
    
        return ( 
          <div className = "App">
            <SearchPhotos onSearch = {this.performSearch} /> 
            <div> 
              {
                (this.state.loading) ? <p>Loading</p> :<PhotoList results={this.state.results} />
              } 
            </div> 
          </div>
        );
      }
    }
    
    export default App;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    import React from 'react';
    
    const PhotoList = props =>
    
        <ul>
            {props.results.map((result, index) =>
                <li key={index}>
                    <img src={result.urls.small} key={result.id} />
                </li>
            )}
        </ul>;
    
    export default PhotoList;

    import React, { Component } from 'react';
    
    
    class SearchPhotos extends Component {
    
        state = {
            searchText: ''
        }
    
        onSearchChange = e => {
            this.setState({
                searchText: e.target.value
            });
        }
    
        handleSubmit = e => {
            e.preventDefault();
            this.props.onSearch(this.query.value);
            e.currentTarget.reset();
        }
    
        render() {
            return(
                <form className="search-form" onSubmit={this.handleSubmit}>
                    <input type="search"
                        onChange={this.onSearchChange}
                        name="search"
                        ref={(input) => this.query = input}
                        placeholder="Search..." />
                    <button className="search-button" type="submit" id="submit">Go!</button>
                </form>
            );
        }
    }
    
    export default SearchPhotos;
    1 回复  |  直到 6 年前
        1
  •  1
  •   Subin Sebastian    6 年前
    performSearch = (query = 'camping') => {
        fetch(`https://api.unsplash.com/search/photos?page=3&query=${query}&client_id=${client_id}`)
          .then(response => response.json())
          .then(responseData => {
            this.setState({
              results: responseData.results,
              loading: false
            });
          })
          .catch(error => {
            console.log('Error fetching and parsing data', error);
          });
      }
    

    响应数据。结果是您要查找的数组。