【问题标题】:Need help on making a nav bar show images from api需要帮助从 api 制作导航栏显示图像
【发布时间】:2019-06-20 05:24:58
【问题描述】:

我是新手,我正在尝试建立一个画廊网站,根据用户点击的按钮显示图片,图片是从 flickr api 获取的,网站看起来像这样

我的 App 组件是使用此功能向 flickr 发出请求的主要组件,因为我能够在搜索输入中搜索图片

//this function will create the search feature
   performSearch = (query = "sunset") => {
     //include a query parameter so that flickr can return images based on user input, and provide a default value for query parameter to display sunset pics when the page first loads
     //fetch data from flickr
     axios 
       .get(
         `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&tags=${query}&per_page=24&format=json&nojsoncallback=1`
       )
       .then(response => { //set the response so that pics will be equal to the data array containing photos from flickr
        console.log(response)
         this.setState({
           pics: response.data.photos.photo, 
           loading: false //initialize a loading state to display a loading message
         });
       })
       .catch(error => { //this catch method outputs a message to the console, should axios fail to retrieve data
         console.log("Something went wrong, could not access data", error);
       });
   }; 

但是,我的目标是渲染来自 CatsDogsComputer 组件的图像,并根据单击的按钮显示图像,但是我不确定该怎么做,这是我的 Cats 组件

import React from "react";

const Cats = () => (
  <div>
    <h2>I want to render cat images as soon as a user click the cats button</h2> {/*pass string as prop from app line 29*/}
    <p>Is it true that cats have 9 lives?</p>
  </div>
);

export default Cats;

我想我应该提到我的 3 个主题位于 Components 文件夹中,而我的 app.js 位于外部,就像这样

任何有用的提示将不胜感激,这是我的参考库https://github.com/SpaceXar20/react_gallery_app_updated

【问题讨论】:

  • 当用户点击该按钮并显示这些图像时,为什么不发送一个获取请求以获取猫的图像......等等......究竟是什么问题?
  • 我想知道是否可以在不创建 Cats、Dogs、Computer 组件的情况下创建该功能
  • 我可以在 App 组件中创建多个 get 请求,

标签: javascript reactjs react-router-v4 react-component


【解决方案1】:

我查看了 repo,它不必要地复杂......这是你可以做的:

四个组件:App.jsForm.jsGallery.jsGalleryItem.js 加上 axios 的辅助方法...

这是您的 App.js:

import React from 'react';

import Form from './Form';
import Gallery from './Gallery';

import flickr from '../utils/flickr';

class App extends React.Component {
  state = { images: [], isLoading: true };

  async componentDidMount() {
    const response = await flickr.get('/services/rest/', {
      params: {
        tags: 'random',
      },
    });
    this.setState({ images: response.data.photos.photo, isLoading: false });
  }

  handleSearch = async term => {
    this.setState({ isLoading: true });
    const response = await flickr.get('/services/rest/', {
      params: {
        tags: term,
      },
    });
    this.setState({ images: response.data.photos.photo, isLoading: false });
  };

  fetchCats = async () => {
    this.setState({ isLoading: true });
    const response = await flickr.get('/services/rest/', {
      params: {
        tags: 'cats',
      },
    });
    this.setState({ images: response.data.photos.photo, isLoading: false });
  };

  fetchDogs = async () => {
    this.setState({ isLoading: true });

    const response = await flickr.get('/services/rest/', {
      params: {
        tags: 'dogs',
      },
    });
    this.setState({ images: response.data.photos.photo, isLoading: false });
  };

  fetchComputers = async () => {
    this.setState({ isLoading: true });

    const response = await flickr.get('/services/rest/', {
      params: {
        tags: 'laptops',
      },
    });
    this.setState({ images: response.data.photos.photo, isLoading: false });
  };

  render() {
    if (this.state.isLoading) {
      return <div className="spinner">Loading...</div>;
    }

    return (
      <div className="photo-container">
        <Form handleSearch={this.handleSearch} />
        <nav className="main-nav">
          <ul>
            <li onClick={this.fetchCats}>CATS</li>
            <li onClick={this.fetchDogs}>DOGS</li>
            <li onClick={this.fetchComputers}>COMPUTERS</li>
          </ul>
        </nav>
        <h2>Results</h2>
        <Gallery images={this.state.images} />
      </div>
    );
  }
}

export default App;

这是您的 Form.js:

import React from 'react';

class Form extends React.Component {
  state = { term: '' };

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  handleSubmit = event => {
    event.preventDefault();
    this.props.handleSearch(this.state.term);
    this.setState({ term: '' });
  };

  render() {
    return (
      <form className="search-form" onSubmit={this.handleSubmit}>
        <input
          type="text"
          name="term"
          placeholder="Search"
          value={this.state.term}
          onChange={this.handleChange}
        />
        <button
          type="submit"
          className="search-button"
          onClick={this.handleSubmit}
        >
          <svg
            fill="#fff"
            height="24"
            viewBox="0 0 23 23"
            width="24"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" />
            <path d="M0 0h24v24H0z" fill="none" />
          </svg>
        </button>
      </form>
    );
  }
}

export default Form;

这是您的 Gallery.js:

import React from 'react';
import GalleryItem from './GalleryItem';

const Gallery = ({ images }) => (
  <ul>
    {images.map(image => {
      return <GalleryItem key={image.id} image={image} />;
    })}
  </ul>
);

export default Gallery;

这是您的 GalleryItem.js:

import React from 'react';

const GalleryItem = ({ image }) => (
  <li>
    {image && (
      <img
        src={`https://farm${image.farm}.staticflickr.com/${image.server}/${
          image.id
        }_${image.secret}.jpg`}
        alt={image.title}
      />
    )}
  </li>
);

export default GalleryItem;

最后是你的 axios 助手:

import axios from 'axios';

const API_KEY = process.env.REACT_APP_FLICKR_KEY; (using the built in .env instead of config...)

export default axios.create({
  baseURL: 'https://api.flickr.com',
  params: {
    method: 'flickr.photos.search',
    per_page: 24,
    format: 'json',
    nojsoncallback: 1,
    api_key: API_KEY,
  },
});

不需要 react-router 恕我直言...

这是一个现场演示(重要提示:在项目的根目录中找到 .env 文件,您会看到类似这样的内容:REACT_APP_FLICKR_KEY=YOUR_API_KEY_HERE。只需将 YOUR_API_KEY_HERE 替换为您的 api 密钥。 ..无需用引号括起来...) https://codesandbox.io/s/n5z516xl2m

【讨论】:

  • 我试图查看演示,我找到了 .env 文件并将我的 api 密钥放在那里,但我得到的只是一个加载消息
  • @ErikL 在一分钟前正在和我一起工作......把你的钥匙放在 = 符号后面......换句话说,'RAECT_APP_FLICKR_KEY=1234examole'
  • @ErikL 玩弄它并尝试了解它是如何工作的......那真是一个折射镜......
  • @ErikL 那里发生了很多事情...如果您有任何问题 - 提问...如果答案有帮助,请接受并点赞...
  • 非常感谢 ypu 抽出宝贵的时间来做这件事,多亏了你,我开始了解 react 和 react router 了很多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
  • 2020-08-10
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多