gpt4 book ai didi

reactjs - 将获取功能放在单独的组件中

转载 作者:行者123 更新时间:2023-12-05 03:01:51 26 4
gpt4 key购买 nike

我正在尝试从以下组件中取出 fetchImages 函数并将其放入一个新组件中:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import UnsplashImage from './UnsplashImage';

const Collage = () => {
const [images, setImages] = useState([]);
const [loaded, setIsLoaded] = useState(false);

const fetchImages = (count = 10) => {
const apiRoot = 'https://api.unsplash.com';
const accessKey =
'<API KEY>';

axios
.get(`${apiRoot}/photos/random?client_id=${accessKey}&count=${count}`)
.then(res => {
console.log(res);
setImages([...images, ...res.data]);
setIsLoaded(true);
});
};

useEffect(() => {
fetchImages();
}, []);

return (
<div className="image-grid">
{loaded
? images.map(image => (
<UnsplashImage
url={image.urls.regular}
key={image.id}
alt={image.description}
/>
))
: ''}
</div>
);
};

export default Collage;

为此,我创建了一个名为 api.js 的新组件,从上面的组件中删除了整个 fetchImage 函数并将其放入 api.js 像这样:

api.js

    const fetchImages = (count = 10) => {
const apiRoot = 'https://api.unsplash.com';
const accessKey =
'<API KEY>';

axios
.get(`${apiRoot}/photos/random?client_id=${accessKey}&count=${count}`)
.then(res => {
console.log(res);
setImages([...images, ...res.data]);
setIsLoaded(true);
});
};

export default fetchImages;

接下来,我从 api.js 中获取 setIsLoaded(true); 并将其粘贴到 Collage 组件中,如下所示:

useEffect(() => {
fetchImages();
setIsLoaded(true);
}, []);

现在我可以将 fetchImages 导入到 Collage 组件中。

但是,我不知道我应该如何处理 fetchImages 函数中的这一行?这需要转到 Collage 组件,但 res.data 未在 Collage 组件内定义。

setImages([...images, ...res.data]);

我该如何处理?

最佳答案

有很多方法可以做到这一点,但在您的情况下。你应该使用

 const fetchImages = (afterComplete, count = 10) => {
const apiRoot = 'https://api.unsplash.com';
const accessKey = '<API KEY>';

axios
.get(`${apiRoot}/photos/random?client_id=${accessKey}&count=${count}`)
.then(res => {
console.log(res);
afterComplete(res.data);
});
};

export default fetchImages;

在您的 Collage 组件中:

const afterComplete = (resData) =>{
setImages([...images, ...resData]);
setIsLoaded(true);
}

useEffect(() => {
fetchImages(afterComplete);
}, []);

关于reactjs - 将获取功能放在单独的组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com