为什么我的图像与文本不同步?

Why Is My Image out of sync with my Text?

我正在尝试 select 在页面加载时从 slides 随机播放一张幻灯片,并将其显示在网站的英雄部分。

但是,图像总是与文本和按钮不同步(例如幻灯片 1 文本和按钮,但显示幻灯片 3 图像),我不知道为什么会这样?

如果幻灯片 1 是幻灯片,则图像、文本和按钮都应显示幻灯片 1 的属性。

export default function Slide() {
  const router = useRouter();

  const slides = [
    {
      img: "/slides/1.webp",
      p: "1",
      label: "1",
      alt: "1",
      url: "/1",
    },
    ...2,...3,...4 // As above but slide 2,3,4
  ];

  const slide = slides[Math.floor(Math.random() * slides.length)];

  return (
    <Flex w="full" h="100%">
      <Flex
        direction={{ base: "column", lg: "row" }}
        justify={{ base: "center", lg: "center" }}
        align="center"
        flex="none"
        boxSize="full"
      >
        <Flex
          mt={{ base: "4", lg: "0" }}
          w={{ base: "90%", lg: "30%" }}
          direction="column"
          justify="center"
          align={{ base: "center", lg: "start" }}
          order={{ base: 2, lg: 1 }}
        >
          <Text
            color="white"
            fontSize={{ base: "2xl", lg: "5xl" }}
            fontWeight="black"
            fontStyle="italic"
            casing="uppercase"
            textAlign={{ base: "center", lg: "left" }}
            lineHeight="short"
          >
            {slide.p}
          </Text>
          <Button
            size="lg"
            mt="8"
            color="white"
            backgroundColor="ss.orange"
            _hover={{ bg: "#CB2106" }}
            fontWeight="bold"
            rounded="none"
            onClick={() => router.push(slide.url)}
          >
            {slide.label}
          </Button>
        </Flex>
        <Flex
          w={{ base: "90%", lg: "50%" }}
          justify={{ base: "center", lg: "end" }}
          order={{ base: 1, lg: 2 }}
        >
          <Image
            width={800}
            height={500}
            layout="intrinsic"
            src={slide.img}
            alt={slide.alt}
            placeholder="blur"
            blurDataURL={slide.img}
            priority
          />
        </Flex>
      </Flex>
    </Flex>
  );
}

这个问题的答案是将逻辑移到 useEffect 中,并使用 useState 来跟踪我们要显示的幻灯片。

const [slide, setSlide] = useState({
      img: "/slides/1.webp",
      p: "1",
      label: "1",
      alt: "1",
      url: "/1",
    })

useEffect(() => {
 const slides = [
    {
      img: "/slides/1.webp",
      p: "1",
      label: "1",
      alt: "1",
      url: "/1",
    },
    ...2,...3,...4 // As above but slide 2,3,4
  ];

  const randomSlide = slides[Math.floor(Math.random() * slides.length)];
  setSlide(randomSlide)
}, [])