通过路由器链接(从“next/link”导入为链接)导航到页面时,默认选择工作正常。但是,当页面重新加载时,默认选择的选项会暂时出现然后消失。
Next.js 13.4.8 React.js 18.2.0
使用新的 Next.js 应用程序路由器。
ShopItem 组件:
"use client"
import Image from 'next/image';
import React, { useState } from 'react';
function ShopItem({ item }) {
// Find the default size object
const defaultSize = item.sizes.find(sizeObj => sizeObj.default) || item.sizes[1]; // Fallback to first size if no default found
// Initialize state to store the currently selected size and price
const [selectedSize, setSelectedSize] = useState(defaultSize.size);
const [selectedPrice, setSelectedPrice] = useState(defaultSize.price);
const handleSizeChange = (size, price) => {
setSelectedSize(size);
setSelectedPrice(price);
};
return (
<div className="shop__item">
<Image
className="shop__item__img"
src={item.image}
width={500}
height={500}
alt={item.name}
/>
<div className="shop__item__content-wrapper">
<h2 className="shop__item__content shop__item__content__name">
{item.name}
</h2>
<div className="shop__item__content__weight-wrapper">
{item.sizes.map((sizeObj, index) => (
<React.Fragment key={index}>
<input
type="radio"
id={`weight-${sizeObj.size}-${item.id}`}
name={`weight-${item.id}`}
value={sizeObj.size}
onChange={() => handleSizeChange(sizeObj.size, sizeObj.price)}
checked={sizeObj.size === selectedSize}
className="visually-hidden"
/>
<label htmlFor={`weight-${sizeObj.size}-${item.id}`} className="button shop__item__content shop__item__content__weight">{sizeObj.size}</label>
</React.Fragment>
))}
</div>
<div className="shop__item__content shop__item__content__price">
{selectedPrice} zł
</div>
<button className="button-big shop__item__content shop__item__content__add-to-cart">
Add to Cart
</button>
</div>
</div>
);
}
export default ShopItem;
在page.js中使用此组件:
import ShopItem from "./shop-item.js";
export default function Shop() {
const items = [
{
id: 1,
name: "Miód rzepakowy",
image: "/img/home/jak-rozpoznac.jpg",
sizes: [
{ size: "250 G", price: 59.9 },
{ size: "450 G", price: 79.9, default: true },
{ size: "1 KG", price: 99.9 }
],
},
{
id: 2,
name: "Miód rzepakowy\nz nutką gryki",
image: "/img/logo.png",
sizes: [
{ size: "250 G", price: 59.9 },
{ size: "450 G", price: 79.9 },
{ size: "1 KG", price: 99.9, default: true }
],
},
];
return (
<main className="page-wrapper main shop">
<div className="shop__1">
{items.map((item) => (
<ShopItem key={item.id} item={item} />
))}
</div>
</main>
);
}
请帮忙^_^
尝试过延迟初始化状态
const [selectedPrice, setSelectedPrice] = useState(() => defaultSize.price);
代替
const [selectedPrice, setSelectedPrice] = useState(defaultSize.price);
还尝试将默认值作为道具传递,认为可能是因为父组件的服务器端渲染。
这是 Next.js 的错误。这里有一些临时解决方案https://github.com/vercel/next.js/issues/49499
当您使用受控输入时,您可以暂时删除“名称”属性,它将起作用