Shirt.size没有按计划更新



我目前正在使用一个端点来访问我的数据库,并根据用户选择的内容为我检索图片,这一切都很好,但当用户选择一种颜色时,什么都没有发生,然后他们选择另一种颜色,最后出现第一个选择,所以情况正好相反。我知道这可能是由于页面的呈现和对象状态的更新引起的,但我不知道如何修复它,这是我当前的代码。

我的状态:

//Keeps track of color user selects
const [color, setColor] = useState("white");

当用户单击颜色时调用的我的updateInCart:

//Updates state color of shirt being selected
const updateColor = async (userColor, shirt) => {
setColor(userColor);
const shirtColorSource = await fetch(
`http://localhost:5000/products/${shirt.product_id}/${color}`
);
const shirtColor = await shirtColorSource.json();
shirt.image = shirtColor[0].image;
console.log(shirt.image);
};

我的useEffect((函数,我认为它不能正常工作rn:

useEffect(() => {
updateColor("white", shirt);
console.log("IN EFFECT");
}, [color])

如何显示图像:

{shirt.map((shirt) => (
<div key={shirt.product_id} className="row">
<div className="col-md-12 col-lg-4 ml-auto">
<img
src={shirt.image}
alt={shirt.name}
className="img-responsive w-100"
/>
</div>

我只是想知道让用户准确地更新图像的最佳方式。

编辑:忘记将颜色放在实际选择的位置:

<div className="row justify-content-center">
<button
onClick={() => updateColor("white", shirt)}
className="button button5 ml-lg-4"
>
{" "}
</button>
<button
onClick={() => updateColor("black", shirt)}
className="button button5 bg-dark mr-lg-4 ml-md-5 mr-md-5"
>
{" "}
</button>
</div>

这也是衬衫的定义方式,使用来自数据库的产品道具:

const { shirtName } = useParams();
const shirt = products.filter((product) => product.name === shirtName);

问题可能来自您的useEffect,它没有告诉所有关于其依赖关系的真相,以及何时执行:

useEffect(() => {
updateColor(color, shirt);
console.log("IN EFFECT");
}, [updateColor, color, shirt])

顺便说一句,你的函数updateColor不是memoized,所以如果你在useEffect中使用它是个问题。考虑将其直接移动到useEffect中(如果未在其他地方使用(,否则使用useCallback声明它。

useEffect(() => {
const updateColor = async (...) => {
...
};
updateColor(color, shirt);
console.log("IN EFFECT");
}, [color, shirt])
// or
const updateColor = useCallback(async (...) => {
...
}, []);
useEffect(() => {
updateColor(color, shirt);
console.log("IN EFFECT");
}, [updateColor, color, shirt])

最新更新