【发布时间】: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