【问题标题】:react I want to add a value to an array of state反应我想向状态数组添加一个值
【发布时间】:2021-01-28 03:52:51
【问题描述】:

开发环境
・ 反应
・ 打字稿

状态组是数组。
我想在调用 onClickGroups 函数时向组数组中添加一个组。 如何实施

interface ISearch {
  name: string;
  age: number;
  groups?: IGroups[];

interface IState {
  searchState: ISearch;
  text: string,
  display: boolean
}

const Index: FC = () => {
  const [state, setState] = useState<IState>({
    searchState: initialSearch,
    text: '',
    display: boolean
  });

  const onClickGroups = (group: IGroups) => {
    setState({ ...state, searchState: { ...state.searchState, groups: group } });
  };

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

您可以对当前组使用spread JavaScript ES6(和 TypeScript)操作,并在数组中添加新的组元素:

const onClickGroups = (group: IGroups) => {
  const currentGroups = state.searchState.groups;
  setState({ 
    ...state,  
    searchState: { 
       ...state.searchState,
       groups: [ ...currentGroups, group ]
    }
  });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-28
    • 2021-04-01
    • 2013-05-27
    • 2019-06-16
    • 2018-11-09
    • 2019-07-11
    • 2019-07-05
    • 2017-10-31
    相关资源
    最近更新 更多