如何更新 reducer 中的 1 属性 个对象?

How can I update 1 property of object in reducer?

我有一个像这样的 reduxreducer:

const initialState = {
    visitedData:{specialty:false,review:false,reviewUpgrade:false}
}

const myred= (state = initialState, action) => {
    switch (action.type) {
        case 'GO_FOR_IT_SON':
            return Object.assign({}, state, { visitedData: action.data });

        default:
            return state
    }
}

现在从我的 reactcomponent 我会调用类似的东西:

 store.dispatch({type: 'GO_FOR_IT_SON', data:{review:true} });

或:

 store.dispatch({type: 'GO_FOR_IT_SON', data:{specialty:false} });

所以这些语句中的每一个都应该将 visitedData 的一个属性设置为 true/false 并保持其他属性不变。 如何将 visitedData 的每个属性设置为 true/false 并保持其他属性不变?

我建议为每个可更改的对象设置一个 reducer 和 action 属性:

import { combineReducers } from 'redux';

const specialty = (state = false, action) => {
  if (action.type === 'TOGGLE_SPECIALTY') {
    return action.data;
  }
  return state;
};

const review = (state = false, action) => {
  if (action.type === 'TOGGLE_REVIEW') {
    return action.data;
  }
  return state;
};

const myred = combineReducers({
  specialty,
  review
});

但在你的情况下,解决方案是:

const myred= (state = initialState, action) => {
  switch (action.type) {
    case 'GO_FOR_IT_SON':
      return Object.assign({}, state, {
        visitedData: Object.assign({}, state.visitedData, action.data)
      });

    default:
      return state
  }
}

我认为这会起作用:

return Object.assign({}, state, {
   visitedData: Object.assign({}, state.visitedData, action.data)
});

检查这个例子:

let a = {b: {a : 1, b : 2, c : 5} };
let b = {a : 5};

let k = Object.assign({}, a, {b: Object.assign({}, a.b, b)});

console.log(k);

一种直接的暴力方式:

编辑使用 lodash cloneDeep

const _ = require('lodash')

let newState = _.cloneDeep(state)

for(let key in action) {
    newState.visitedData[key] = action[key]
}

与其他解决方案相同。我建议将对象合并到另一行中,并使用对象展开以获得更高的可读性

const myred = (state = initialState, action) => {
  switch (action.type) {
    case 'GO_FOR_IT_SON':
      let newVisitedData = {
        ...state.visitedData,
        ...action.data
      }
      return { visitedData: newVisitedData }
    default:
      return state
  }
}

const initialState = {
      visitedData: {
      specialty: false,
      review: false,
      reviewUpgrade: false
    }
}

const myred = (state = initialState, action) => {
    switch (action.type) {
        case 'GO_FOR_IT_SON':
            return {...state, visitedData: {...state.visitedData, action.data}}
        default:
            return state
    }
}

正如您对状态所做的那样 - Object.assign,您应该对 visitedData 对象执行相同的操作,或者改用扩展运算符 object.assign