简体   繁体   中英

How do I console.log state.car.price in my reducer function

I can't seem to access a property that's nested within an object. I want to have my app up and running but I cannot get passed this bug.


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)
}; 

How are you calling featuresReducer? If you're only passing one parameter, it would go in the state variable, and if you pass it two variables, it would overwrite the initialState default.

You are returning in the switch statement before the console.log is executed. Also I think you have a ":" where you meant to use a ",".Try something like this:

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;
  }
}; 

If you want to see the state.car.price you'll have to call console.log after the reducer action is performed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM