我正在尝试从API提取数据,并将响应传递给img src,它显示状态值为“未定义”。在下面的代码中,我尝试在useEffect中设置“ bannerImage”状态,并抛出“ undefined”。我也尝试使用普通函数,将“ bannerImage”设置为空值。
注意:then语句中的“ res”值显示的是网址,但设置为仅声明其无效时。
function Carousel(props) {
let CarouselSettings = CarouselSetting.homePageBannerCarousel;
const [bannerImage, setBannerImage] = useState();
const serviceEndpoint = config.serviceHost + "/mycompany";
useEffect(() => {
props.carouselData.map((data) => {
//setBannerDetail(data);
return axios
.get(
serviceEndpoint +
config.apiUrl.getAllAppImage +
"/?id=" +
data.pbDtlId +
"&&vendorId=1" +
"&&filecatcode=" +
getFilecatcode.banner
)
.then(res => setBannerImage(res );
});
});
console.log(bannerImage, "===banner");
return (
// <div className="pt-40">
<div className="slider-wrapper relative top-130 py-8 px-10 bg-gray-100">
<Slider {...CarouselSettings}>
{props.carouselData.map((data) => {
return (
<div>
<div>
<h1 className="text-3xl font-semibold">{data.bannerTitle}</h1>
<h4 className="text-xl py-5">
{data.bannerDesc1} {data.bannerDesc2}
</h4>
<h4 className="text-xl pb-5">{data.bannerDesc3}</h4>
<img src={bannerImage}/>
</div>
</div>
);
})}
</Slider>
</div>
);
}
export default Carousel;
答案 0 :(得分:1)
为每个项目设置图像,而不是对轮播数据中的所有项目使用相同的变量。在您的useEffect
循环轮播数据中,并为src添加另一个道具。
function Carousel({ carouselData }) {
let CarouselSettings = CarouselSetting.homePageBannerCarousel;
const [carousel, setCarousel] = useState([]);
const serviceEndpoint = config.serviceHost + "/mycompany";
useEffect(() => {
const getBannerImages = async () => {
const data = await Promise.all(carouselData.map(async (item) => {
// get the image url and set it to the item and access it in your render with data.src
const src = await axios.get(
serviceEndpoint +
config.apiUrl.getAllAppImage +
"/?id=" +
item.pbDtlId +
"&&vendorId=1" +
"&&filecatcode=" +
getFilecatcode.banner)
return {
...item,
src
}
}));
setCarousel(data);
}
getBannerImages()
.catch(e => console.log(e));
}, [carouselData]);
return (
// <div className="pt-40">
<div className="slider-wrapper relative top-130 py-8 px-10 bg-gray-100">
<Slider {...CarouselSettings}>
{carousel.map((data) => {
return (
<div>
<div>
<h1 className="text-3xl font-semibold">{data.bannerTitle}</h1>
<h4 className="text-xl py-5">
{data.bannerDesc1} {data.bannerDesc2}
</h4>
<h4 className="text-xl pb-5">{data.bannerDesc3}</h4>
<img src={data.src}/>
</div>
</div>
);
})}
</Slider>
</div>
);
}
export default Carousel;
答案 1 :(得分:0)
尝试以下方法,
useEffect(() => {
props.carouselData.map((data) => {
//setBannerDetail(data);
return axios
.get(
serviceEndpoint +
config.apiUrl.getAllAppImage +
"/?id=" +
data.pbDtlId +
"&&vendorId=1" +
"&&filecatcode=" +
getFilecatcode.banner
)
.then(res => {
setBannerImage(res);
});
});
}, []);