反应我想向状态数组添加一个值

时间:2020-10-13 18:55:44

标签: reactjs typescript

发展环境
・反应
・打字稿

状态组是数组。
我想在调用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 } });
  };

1 个答案:

答案 0 :(得分:4)

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

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