如何修复反应代码,有时效果很好,有时效果不佳

时间:2019-09-25 08:26:49

标签: reactjs

我不会做一个应用程序,该应用程序可以获取当天NASA图片的一些图片。我展示了今天的图片和一些(例如4张)以前的图片。我使用datepicker根据自己的选择来选择日期的图像。问题是有时工作正常,有时仅显示今天的照片,有时今天仅显示前一张或两张。有人可以解释发生了什么事吗?

我已经重置了cookie,可以在Firefox和Chromium上尝试。我使用DEMO_KEY上传代码,但在我的应用中使用注册后收到的密钥。

App.js:

import React, { Component } from "react";
import DateInput from "./components/DateInput.js";
import Photo from "./components/Photo.js";
import Axios from "axios";

class App extends Component {
  state = {
    date: new Date(),
    currentPhoto: "",
    photos:[]
     };
   componentDidMount(){
    Axios
       .get(`https://api.nasa.gov/planetary/apod?&api_key=DEMO_KEY`)
       .then(response => this.setState({currentPhoto: response.data}));
    this.getImages(5);
     }
   getImages = n => {
    const daysBuffer = [];
 for(let i=1; i<n; i++){      
      let today = new Date();
      today.setDate(today.getDate()-i);
       daysBuffer.push(today);
    }
    const picBuffer = [];
    const datesBuffer = daysBuffer.map(day => this.getDate(day));
   datesBuffer.map(date => {
      Axios
       .get(`https://api.nasa.gov/planetary/apod?date=${date}&api_key=DEMO_KEY`)
       .then(response => picBuffer.push(response.data));
    })
    this.setState({photos: picBuffer});
  }
  getDate = time => {
    let year = time.getFullYear();
    let month = time.getMonth();
    let day = time.getDate();
      return (
         `${year}-${month}-${day}`
        )
    };
   getPhoto = a => {
    let date = this.getDate(a);
    Axios
     .get(`https://api.nasa.gov/planetary/apod?date=${date}&api_key=DEMO_KEY`)
     .then(response => this.setState({currentPhoto: response.data}))
  }
  changeDate = date => {
   this.setState({
    date
   });
   this.getPhoto(date);
  }
  render() {
      const imageGrid = this.state.photos.map(pic => {

               return (
                <ul>
                 <Photo photo = {pic} key={pic.date} />
                </ul>
                )
     })
    return (
      <div>
        <h1>NASA's Astronomy Picture of the Day</h1>
       <DateInput 
                 changeDate = {this.changeDate}
                 date = {this.state.date}
                 />
                 <Photo photo = {this.state.currentPhoto} />
                 {imageGrid}
      </div>
    );
  }
}

export default App;

DateInput.js:

import React from "react";
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";

const DateInput = props => (
  <div>
   Select a Date: 
   <DatePicker

    selected = {props.date}
    onChange = {props.changeDate}
   />
  </div>
);

export default DateInput;

Photo.js

import React from 'react';

const Photo = props => (
      <div>
        <h3>{props.photo.title}</h3>
        <img src={props.photo.url} alt={props.photo.title} />
        <p>{props.photo.explanation}</p>

      </div>
    )

export default Photo;

1 个答案:

答案 0 :(得分:0)

代码中最可能出现的问题是,在异步检索图像时您正在执行同步操作。 主要问题在于您的 getImages 函数

getImages = n => {
  const daysBuffer = [];
  for(let i=1; i<n; i++){      
    let today = new Date();
    today.setDate(today.getDate()-i);
    daysBuffer.push(today);
  }
  const picBuffer = [];
  const datesBuffer = daysBuffer.map(day => this.getDate(day));
  datesBuffer.map(date => {
    Axios
      .get(`https://api.nasa.gov/planetary/apod?date=${date}&api_key=DEMO_KEY`)
      .then(response => picBuffer.push(response.data));
  })
  this.setState({photos: picBuffer}); //this line runs before Axios finishes
}

要解决此问题,而不必转移到异步/等待(更好,但需要进行重组),则必须将最后几行更改为此:

datesBuffer.map(date => {
  Axios
    .get(`https://api.nasa.gov/planetary/apod?date=${date}&api_key=DEMO_KEY`)
    .then(response => {
      picBuffer.push(response.data);
      this.setState({photos: picBuffer});
    })
})

请注意,它现在多次设置状态,这并不理想,但是如果不了解Axios在异步/等待方面的功能,这将是最合乎逻辑的解决方案。