React TypeScript:如何在嵌套状态对象的其他值中传播

时间:2019-12-03 07:12:38

标签: reactjs typescript

在共享中更新单个值时,如何在其他现有值中传播

interface StateInterface {
  env: {
    apiUrl: string;
  };
  display: {
    modal: string;
  };
  shared: {
    avatar: string;
    email: string;
    fullName: string;
    loggedIn: boolean;
    language: string;
    warningMessage: string;
  };
}

const InitialState: StateInterface = {
  env: {
    apiUrl: 'http://localhost:8888',
  },
  display: {
    modal: '',
  },
  shared: {
    avatar: '',
    email: '',
    fullName: 'John Doe',
    language: 'en',
    loggedIn: false,
    warningMessage: '',
  },
};

const Reducer = (state: StateInterface, action: any) => {
  switch (action.type) {
    case 'SET_AVATAR':
      return {
        ...state,
        shared: {avatar: action.value}, // <<-- Will the other items in shared get overwriten, if so how to spread them in?
      };
 ...

1 个答案:

答案 0 :(得分:5)

 return {
        ...state,
        shared: {...state.shared, avatar: action.value}, // <<-- Will the other items in shared get overwriten, if so how to spread them in?
      };