-1

我正在尝试将一个对象分配给另一个具有相同类型的对象。

所以,我有这个对象'语言'

export class Language {
  languageDescription: string;
  languageCode: string;
  isDefault: boolean;
}

我声明了两个对象和selectedLanguage语言类型childSelectedLanguage

@State<LanguageSelectorStateModel>({
  name: 'languageSelector',
  defaults: {
    languages: [],
    selectedLanguage: null,
    childSelectedLanguage: null
  }
})*

填充 selectedLanguage 后(不再为空),

  @Action(UpdateSelectedLanguage)
  @ImmutableContext()
  updateSelectedLanguage({ getState, patchState }: StateContext<LanguageSelectorStateModel>, { languageCode }: UpdateSelectedLanguage) {
    const state = getState();
    const selectedLanguage = state.languages.find(language => language.languageCode === languageCode);
    state.selectedLanguage = selectedLanguage;
    patchState(state);
  }

我试图将此值的相同内容分配给 childSelectedLanguage。

childSelectedLanguage = selectedLanguage;

但是 childSlectedLanguage 仍然为空,尽管 selectedLanguage 不是。

我也试过

  @Action(InitializeChildrenSelectedLanguage)
  initializeChildrenSelectedLanguage(
    { getState, patchState }: StateContext<LanguageSelectorStateModel>,
    {  }: InitializeChildrenSelectedLanguage
  ) {
    const state = getState();
    Object.assign(state.childSelectedLanguage, state.selectedLanguage);
    patchState(state);
  }

但我也无法将对象分配给内容。

第一个问题:为什么我不能分配对象?

第二个问题:我该如何解决这个问题?

4

1 回答 1

0

要从另一个对象创建对象,您可以使用这种函数

/**
 * Update attributes of Class or object.
 *
 * @param origin - Original Object
 * @param newValues - New Values
 */
export function updateFields<T>(origin: T, newValues: Partial<T>): T {
  if (typeof origin !== 'object' || typeof newValues !== 'object') {
    throw new Error('Arguments must be kind of Classe or Object');
  }

  const keys = (Object.keys(newValues) as unknown) as Array<keyof T>;
  const result = origin; // Reassignment of Function Parameters is prohibited so we do a copy.

  keys.forEach(function affectValues(key) {
    result[key] = newValues[key] as never;
  });
  return result;
}

在您的代码中,您可以执行此操作

state.selectedLanguage = updateFields<YourType>(state.selectedLanguage, selectedLanguage);
于 2020-11-13T00:46:50.900 回答