【问题标题】:ReactJS save output of a fetch to a var?ReactJS 将 fetch 的输出保存到 var?
【发布时间】:2018-03-19 19:38:27
【问题描述】:

又是我,我仍在使用 ReactJS 前端和 NodeJS 后端开发我的收藏项目。

今天我正在尝试添加一个函数“onClick”,我在其中设置了一个新的 urlImages 数组。

为了做到这一点,我必须将我的 fetch 输出的值保存在一个名为“obj”的变量中,这样我就可以在另一个 fetch 中再次使用它。这样做的重点是当我点击一个集合的图像,它设置了一个新的 urlimages 数组,它将获取属于该集合的图像的 url。

这不应该那么难,但我在做那件事时遇到了麻烦..有人可以帮助我吗?

import React from 'react';
import { render } from 'react-dom';
import Gallery from 'react-photo-gallery';
import Photo from './Photo';


class PhotoGallery extends React.Component {
  constructor(props){
    super(props);
    this.onClick = this.onClick.bind(this);
    this.state = {
      urlImages: [],
      nomCollection: []
    };
  }
  async componentDidMount() {
    const response = await fetch("http://localhost:3004/getUrlImages");
    const newList = await response.json();
    this.setState(previousState => ({
      ...previousState,
      urlImages: newList,
     }));
  }

  galleryPhotos() {
   if(this.state.urlImages) {
      return this.state.urlImages.map(function(urlimage) {
         return { src: urlimage.urlimage, width: 2, height: 2 }
      })
   }
}

  async onClick(event) {

    const rawObj = await fetch("http://localhost:3004/getCollectionFromUrlImage?urlimage="+event.target.src);
    const obj = await rawObj.json();

    const response = await fetch("http://localhost:3004/getUrlImagesFromCollection?collection="+obj[0].nom);
    const newList = await response.json();

    this.setState(previousState => ({
      ...previousState,
      urlImages: newList,
     }));
  }

  render() {
    return (
      <Gallery axis={"xy"} photos={this.galleryPhotos()} onClick={this.onClick}/>
    )
  }
}
const photos = [];
export default PhotoGallery;
<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>

我的 json 的响应是:

[{"nom":"Cartes"}]

console.log 显示:

0: {nom: "Cartes"}

length: 1

__proto__: Array(0)

BUUT alert(obj) 显示 undefined

有什么帮助吗?我希望 obj 等于“Cartes”..

提前谢谢大家:)

【问题讨论】:

  • wait...你在componentDidMount中使用了async/await并正确获取,你为什么不在onclick中使用相同的技术?在不理解的情况下复制/粘贴?
  • 我以为我理解得很好,我也尝试过异步等待,但没有得到我想要的结果,所以我尝试了不同的方法,认为两次提取会有所不同.. =/
  • 你需要两次等待,就像第一种情况一样。 fetch 返回一个 Promise,它解析为一个响应,然后您需要调用 .json() ,它也返回一个 Promise。
  • 是的,我已经尝试过了,但无法将 obj 的值设置为“Cartes”。我已经更新了我的原始代码,你能看一下吗?

标签: javascript reactjs api output fetch


【解决方案1】:

您需要await 第一次提取,就像您对第二次所做的那样:

const rawObj = await fetch("http://localhost:3004/getCollectionFromUrlImage?urlimage="+event.target.src);
const obj = await rawObj.json();

onClick 方法中的第二次获取在您的服务器有机会响应第一次获取之前运行,因为您没有 await 它。

【讨论】:

  • 嘿,伙计,我已经尝试过您的方法,但是当我执行 console.log() 时,它会向我显示承诺值。我认为关于 fetch 仍有一点我不明白,var obj 现在不应该等于“Cartes”吗?或至少一个包含字符串的数组?
  • 请看我的编辑,我忘了json() 也返回一个承诺。
  • 谢谢我再次编辑它,我得到一个数组,第一个字符串为“Cartes”。但是原谅我知识的匮乏,怎么能把数组的字符串值直接放到变量中呢?响应是一个数组,所以 obj[0] 不应该给我第一个值吗?我很困惑
  • 查看你的数据结构obj[0]会得到{nom: 'Cartes'},然后你可以通过obj[0].nom得到字符串
  • 天哪,我终于成功了。非常感谢您的时间和帮助。问题现已解决,我已在原始帖子中更新了解决方案
猜你喜欢
  • 2021-08-09
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 2021-11-12
  • 2020-12-29
  • 2016-02-28
  • 2011-11-10
相关资源
最近更新 更多