React中Carousel组件不显示问题求助(附相关代码)
问题:React Carousel组件不显示服务器返回的新闻数据
已确认服务器正常返回新闻数据,但react-responsive-carousel组件既不展示内容,也未抛出任何错误。以下是相关代码文件:
News.tsx
import React from 'react'; import './News.css'; interface INews{ name: string; description: string; imageUrl: string; onClick: () => void; } function News({name, description, imageUrl, onClick} : INews) { return ( <div className='news'> <h1>{name}</h1> <p>{description}</p> <img src={imageUrl} alt="img news" /> <button onClick={onClick} className='imgBut' title="Enter"/> </div> ); } export default News;
MyCarosel.tsx
import React from "react"; import { Carousel } from "react-responsive-carousel"; import News from "../News/News"; import { New } from "../../Entity/News"; const items: New[] = []; const MyCarousel = ({ items }: { items: New[] }) => { const enterClick = () => { // Handle the button click event here console.log('Button clicked!'); }; return ( <Carousel className="myCar"> {items.map((item) => ( <News name = {item.name} description= {item.description} imageUrl= {item.imageUrl} onClick= {enterClick} /> ))} </Carousel> ); }; export default MyCarousel;
Home.tsx
import React, { useEffect } from 'react'; import './Home.css'; import Header from '../Headers/Header'; import Fotter from '../Fotter/Fotter'; import { getNews } from '../../ApiService/ApiService'; import MyCarousel from '../MyCarosel/MyCarosel'; import { New } from '../../Entity/News'; function Home() { let news: New[] = []; //get news useEffect(() => { // Викликаємо функцію при завантаженні сторінки getNews() .then(data => { // Отримані дані доступні тут news = data; }) .catch(error => { // Обробка помилки console.error(error); }); }, []); return ( <div> <Header/> <div> <MyCarousel items={news}/> </div> <Fotter/> </div> ); } export default Home;
New.tsx
export class New{ id: Int32Array; name: string; description: string; imageUrl: string; constructor(id: Int32Array, name: string, description: string, imageUrl: string) { this.id = id; this.name = name; this.description = description; this.imageUrl = imageUrl; } };
问题排查与修复方案
1. 未使用React状态管理异步数据
Home组件中用普通变量news存储异步获取的数据,React无法监听普通变量的变化,数据更新后不会触发组件重渲染,导致Carousel始终接收到空数组。
修复代码:
import React, { useEffect, useState } from 'react'; // ...保留其他导入 function Home() { // 用useState替代普通变量,初始化空数组 const [news, setNews] = useState<New[]>([]); useEffect(() => { getNews() .then(data => { setNews(data); // 通过setNews更新状态,触发重渲染 }) .catch(error => { console.error(error); }); }, []); // 返回部分保持不变 }
2. New类的id类型错误
id被定义为Int32Array类型,但服务器返回的id通常是数字(number类型),类型不匹配可能导致数据解析或渲染异常。
修复代码:
export class New{ id: number; // 将Int32Array替换为number name: string; description: string; imageUrl: string; constructor(id: number, name: string, description: string, imageUrl: string) { this.id = id; this.name = name; this.description = description; this.imageUrl = imageUrl; } };
3. 遗漏react-responsive-carousel的样式导入
react-responsive-carousel依赖内置样式才能正常显示,缺失样式会导致组件不可见(无报错)。
修复代码: 在MyCarosel.tsx中添加样式导入:
import React from "react"; import { Carousel } from "react-responsive-carousel"; // 添加这行样式导入 import "react-responsive-carousel/lib/styles/carousel.min.css"; import News from "../News/News"; import { New } from "../../Entity/News"; // ...保留其他组件代码
4. 可选优化:为列表项添加唯一key
在map渲染时添加唯一key属性,提升React渲染性能并避免控制台警告:
{items.map((item) => ( <News key={item.id} // 添加唯一key,推荐使用数据的唯一标识 name={item.name} description={item.description} imageUrl={item.imageUrl} onClick={enterClick} /> ))}
内容的提问来源于stack exchange,提问作者Владислав Мельник
相关产品推荐
相关产品推荐

