reactjs 服务器错误类型错误:无法析构“sliderItem[index]”的属性“image”,因为它未定义

68bkxrlz  于 2023-03-22  发布在  React
关注(0)|答案(1)|浏览(74)

我试图创建一个滑块与nexjs和类型脚本,但我得到下面的错误时,我析构一个数组的对象
服务器错误
TypeError:无法解构“sliderItem[index]”的属性“image”,因为该属性未定义。生成页面时发生此错误。所有控制台日志都将显示在终端窗口中。Source
components/Slider/Slider.tsx(53:10)@ image
五十一|}; 52|
五十三|const {图像、名称、标题、引用} =幻灯片项[索引];

import Image from 'next/image';
import React, { useEffect, useState } from 'react';
import { MdArrowForwardIos, MdArrowBackIosNew } from 'react-icons/md';
const url = 'http://localhost:3004/people';
export type SliderProps = {
  id: number;
  image: string;
  name: string;
  title: string;
  quote: string;
};

function Slider() {
  const [index, setIndex] = useState<number>(0);
  const [sliderItem, setSliderItem] = useState<SliderProps[]>([]);

  const fetchData = async () => {
    const res = await fetch(url);
    const data = await res.json();
    setSliderItem(data);
  };

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

  useEffect(() => {
    setInterval(() => {
      if (index === sliderItem.length - 1) {
        setIndex(0);
      } else {
        setIndex(index + 1);
      }
    }, 300000);
  }, [index, sliderItem]);

  const slideLeft = () => {
    if (index === 0) {
      setIndex(sliderItem.length - 1);
    } else {
      setIndex(index - 1);
    }
  };
  const slideRight = () => {
    if (index === sliderItem.length - 1) {
      setIndex(0);
    } else {
      setIndex(index + 1);
    }
  };

  const { image, name, title, quote } = sliderItem[index];
  return (
    <div className='max-w-5xl mx-auto '>
      <div className='grid grid-cols-1 mt-20 place-items-center'>
        <div className='flex flex-col items-center justify-center max-w-3xl gap-2 '>
          <div className='w-32 p-1 rounded-full bg-violet-200'>
            <img
              src={image}
              alt={title}
              className='object-cover w-32 h-32 rounded-full '
            />
          </div>
          <div className='flex items-center justify-between w-full gap-5 '>
            <button onClick={slideLeft} className='items-center text-3xl'>
              <MdArrowBackIosNew />
            </button>
            <div>
              <h3 className='text-3xl text-center text-violet-800'>{name}</h3>
              <h4 className='text-center '>{title}</h4>
            </div>
            <button onClick={slideRight}>
              <MdArrowForwardIos />
            </button>
          </div>
          <p className='text-center '>{quote}</p>
        </div>
      </div>
    </div>
  );
}
export default Slider;
ttvkxqim

ttvkxqim1#

在第一次呈现sliderItem时,sliderItem是空数组,就像在useState中传递的一样。因此,即使在index=0时也没有项。您可以在加载数据时显示某种微调器,或者,如果您没有特定的模式来处理应用程序中的加载,最简单的修复方法是在解构行之前返回null

if(sliderItem.length === 0) {
   return null;
}
const { image, name, title, quote } = sliderItem[index];
return (
  <div className='max-w-5xl mx-auto '>
  ....

相关问题