我正在嘗試開發一個帶有產品詳細資訊頁面的電子商務網站。用戶可以選擇產品的可用選項。假設我選擇了一只鞋子并選擇了尺碼 42,當我點擊“添加到購物車”按鈕時,它會觸發handleAddToCart一次。完成后,如果用戶想要添加不同的變體,他只需單擊differentVariationBox然后再次單擊“添加到購物車”,這應該會將新選擇的產品添加到購物車
錯誤僅在handleAddToCart執行后出現,并handleVariation會導致錯誤。我想知道為什么會發生這個錯誤以及如何解決它。
當我嘗試更改產品選項時,出現以下錯誤

const handleAddToCart = () => {
// The selected variation is an array which track the selected attributes but its
// order depends on the user click on the attributeswe need to sort them in the order we have
// Received from the server because we will create an unique key for the cart item to know if the
// Product is alredy in cart with same attributes
// ?? example i order shoe with id black-puma with size 42 and color black
// The id will become black-puma size=42 color=black now i can track weather this variation product exist
const order = product.attributes.map((attribute) =>
this.state.selected_variation.find((v) => v.type === attribute.id)
);
// Checking if the length of the variation is equal to the length of the attributes
// This will ensure all the variation is selected
if (this.state.selected_variation.length ===product.attributes.length) {
const data = {
variation: order,
product: product,
quantity: this.state.quantity,
id:`${product.id} ${order.map((item) => `${item.type}=${item.value}`).join(" ")}`
};
this.props.addToCart(data);
} else {
alert("Please Select all the variations or The selected variation is already exist in the cart");
}
};
// Function that will handle the variation selection
const handleVariation = (e) =>{
let type = e.target.name;
let value = e.target.value;
// Checking is the selected attribute exist
let index = this.state.selected_variation.findIndex((x)=>{
return x.type === type
})
// if not exist then add it
if(index === -1){
this.setState({
selected_variation: [...this.state.selected_variation, {type,value}]
})
}else{
const newData = [...this.state.selected_variation];
newData[index].value = value
this.setState({
selected_variation:newData,
})
}
}
SO句柄變化觸發時
任何變化都是變化句柄變化將在輸入無線電狀態發生變化時觸發
uj5u.com熱心網友回復:
您的代碼有問題:
else{
const newData = [...this.state.selected_variation];
newData[index].value = value
this.setState({
selected_variation:newData,
})
}
首先,您使用傳播復制了舊狀態。就像您剛剛創建了新陣列一樣,但陣列元素正在從當前狀態參考相同的元素(參考未修改,因為您僅在頂層淺層復制了陣列)。之后,您訪問了帶有索引的元素,并且由于陣列中的newData[index]元素沒有直接從this.state. 由于您嘗試直接改變狀態,因此 react 會引發錯誤,因此它不會讓您這樣做,因為它希望僅使用this.setState.
重寫為:
else{
this.setState(prevState => ({selected_variation:
prevState.selected_variation.map((el, ind) => ind === index ? { ...el, value} : el })
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/497433.html
標籤:javascript 反应
上一篇:如何在JSX(ReactNative)中渲染二維陣列?
下一篇:更新的全域變數未傳遞到字串
