为什么我的新字符串值在 React.js 中未定义?

Why is my new string value undefined in React.js?

我正在 React.js 构建一个购物车,并且一切正常。除了价格、描述、标题和图像等现有字符串值外,我还想添加一个 SKU 值。在我的 cartReducer.js 文件中,我有以下内容:

import Item1 from './images/apple_gala.jpg';
import Item2 from './images/apple_greenleaf.jpg'
import Item3 from './images/apple_granny.jpg'
import Item4 from './images/apple_pinklady.jpg'
import { ADD_TO_CART, REMOVE_ITEM } from '../actions/action-types/cart-actions.js'

const initState = {
    items: [
        {id:1,title:'Royal Gala', desc: "Gala apples have a blush of pink in their skin. It’s dense, sweet juicy flesh makes it ideal for eating fresh.", price:7,SKU:A,img:Item1},
        {id:2,title:'Greenleaf', desc: "Our own original produce, the Greenleaf Original apple is award winning for the crispness of it's skin.",price:8,SKU:B,img: Item2},
        {id:3,title:'Granny Smith', desc: "Our French Granny Smith apples have a distinct sharp taste – perfect for eating fresh or using in cooking.", price:5,SKU:C,img: Item3},
        {id:4,title:'Pink Lady', desc: "A distinct and refreshing flavour with uniquely pink colouring - it can only be our Pink Lady apples.", price:5,SKU:D,img: Item4},
    ],
    addedItems:[],
    total: 0

}
const cartReducer= (state = initState,action)=>{

    if(action.type === ADD_TO_CART){
          let addedItem = state.items.find(item=> item.id === action.id)

         let existed_item= state.addedItems.find(item=> action.id === item.id)
         if(existed_item)
         {
            addedItem.quantity += 1 
             return{
                ...state,
                 total: state.total + addedItem.price 
                  }
        }
         else{
            addedItem.quantity = 1;

            let newTotal = state.total + addedItem.price 

            return{
                ...state,
                addedItems: [...state.addedItems, addedItem],
                total : newTotal
            }

        }
    }
    if(action.type === REMOVE_ITEM){
        let itemToRemove= state.addedItems.find(item=> action.id === item.id)
        let new_items = state.addedItems.filter(item=> action.id !== item.id)

        let newTotal = state.total - (itemToRemove.price * itemToRemove.quantity )
        console.log(itemToRemove)
        return{
            ...state,
            addedItems: new_items,
            total: newTotal
        }
    }

  else{
    return state
    }

}

export default cartReducer

在项目数组中我有 4 个项目,在最右边我有新添加的 SKU 值,简单的 ABCD。当我保存文件时,出现编译失败错误,因为 A、B、C 和 D 都未定义。奇怪的是其他字符串值也没有在任何地方定义,那么为什么 SKU 失败了?

如有任何帮助,我们将不胜感激!

你在哪里定义了A、B、C变量?您在这里将它们用作变量而不是字符串。您需要将它们放在引号中以使它们成为字符串文字。

{id:1,title:'Royal Gala', desc: "Gala apples have a blush of pink in their skin. It’s dense, sweet juicy flesh makes it ideal for eating fresh.", price:7,SKU:"A",img:Item1},

这就是您仅在 SKU 上收到此错误的原因