英文:
Can anyone explain.Why the 'res" is getting logged two times?
问题
我试图从Flickr获取图像数据。我已经收到了响应,但无法显示图像。我尝试使用useEffect
来获取API并使用useState
变量来存储图像数组。但仍然被调用了两次。
const DisplayImages = () => {
let photos = [];
fetch(
`https://www.flickr.com/services/rest/?method=flickr.galleries.getPhotos&api_key=***********************&gallery_id=************&format=json&nojsoncallback=1`
)
.then((response) => response.json())
.then((res) => {
const images = res;
console.log(res);
photos = images.photos.photo;
});
return (
<>
<div className="imagescontainer">
{photos.map((photo) => {
console.log(photo);
let url = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}`;
<>
{/* <img src={require(url)} alt="img" /> */}
</>
})}
</div>
</>
);
};
我期望图像被呈现。
英文:
I am trying to get the images data from flickr. I am getting the response but not able to display the image.I have tried using useEffect to fetch the api and useState variable to store images array. Still it was getting called two times.
const DisplayImages = () => {
let photos = [];
fetch(
` https://www.flickr.com/services/rest/?method=flickr.galleries.getPhotos&api_key=***********************&gallery_id=************&format=json&nojsoncallback=1`
)
.then((response) => response.json())
.then((res) => {
const images = res;
console.log(res);
photos = images.photos.photo;
});
return (
<>
<div className="imagescontainer">
{photos.map((photo) => {
console.log(photo);
let url = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}`;
<>
{/* <img src={require(url)} alt="img" /> */}
</>
})}
</div>
</>
);
};
I expected the images to be rendered.
答案1
得分: 1
因为 React 可能配置为 严格模式(应该是这样),所以它被调用两次。在开发中,严格模式故意导致 hooks 被调用两次。这是有意的,你需要在编写 React 组件时考虑到这一点。
其次,你正在使用一个局部作用域变量 photos
来保存状态,而你需要使用 useState
实例,否则 React 不会知道状态何时更改并重新渲染组件。
第三,看起来你正在将 photos
,它初始化为空数组,设置为单个照片实例。
英文:
It's getting called twice because React is probably configured to be in strict mode (as it should be). In development, strict mode causes hooks to be called twice on purpose. This is intentional and you'll need to write your React components with this in mind.
Second, you're using a locally-scoped variable photos
to hold state, when you need to use useState
instance, otherwise React won't know when the state changes and re-render the component.
Third, it looks like you're setting photos
, which is initialized with an empty array, to a single instance of a photo.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论