【问题标题】:How to fix react code which sometimes work fine sometimes not如何修复有时可以正常工作有时不能正常工作的反应代码
【发布时间】:2019-09-25 08:26:49
【问题描述】:

我不会制作一个应用程序来获取 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;

日期输入.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;

【问题讨论】:

  • 您的描述不清楚。
  • 在解析图像时,您似乎缺少了一些 asyncawait 关键字。
  • NASA API 有速率限制。也许这就是导致问题的原因

标签: reactjs


【解决方案1】:

您的代码中最可能出现的问题是,您在异步检索图像时采取了同步操作。 主要问题在于您的 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
}

要解决此问题,无需转向 async/await(这更好,但需要重组),您必须将最后几行更改为:

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 关于 async/await 的能力的情况下,这将是最合乎逻辑的解决方案。

【讨论】:

  • 你说得对,我按照你说的修好了,现在一切正常。谢谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 2023-02-06
  • 2015-06-06
  • 2016-01-09
  • 1970-01-01
相关资源
最近更新 更多