首页 > 解决方案 > 如何在我的减速器功能中 console.log state.car.price

问题描述

我似乎无法访问嵌套在对象中的属性。我想让我的应用程序启动并运行,但我无法通过这个错误。


const initialState = {
  additionalPrice: 0,
  title:"hi",
    car: {
      price: 26395,
      name: '2019 Ford Mustang',
      image:
        'https://cdn.motor1.com/images/mgl/0AN2V/s1/2019-ford-mustang-bullitt.jpg',
      features: []
    },
    additionalFeatures: [
      { id: 1, name: 'V-6 engine', price: 1500 },
      { id: 2, name: 'Racing detail package', price: 1500 },
      { id: 3, name: 'Premium sound system', price: 500 },
      { id: 4, name: 'Rear spoiler', price: 250 }
    ]
};

export const featuresReducer = (state = initialState, action) => {
  console.log(action, state);
  switch (action.type) {
    case ADD_FEATURE:
      return {
        ...state,
       ...state.car:{...state.car:price:5}
      }
    default:
      return state;
  }
  console.log(state.car.price)
}; 

标签: reactjsreduxreact-redux

解决方案


您在执行 console.log 之前返回 switch 语句。另外我认为你有一个“:”,你的意思是使用一个“,”。试试这样的东西:

export const featuresReducer = (state = initialState, action) => {
  console.log(action, state);
  switch (action.type) {
    case ADD_FEATURE:
      console.log("here");
      return {
        ...state,
        car: { ...state.car, price: 5 }
      }
    default:
      return state;
  }
}; 

如果您想查看 state.car.price,您必须在执行 reducer 操作后调用 console.log。


推荐阅读