发展环境
・反应
・打字稿
状态组是数组。
我想在调用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 } });
};
答案 0 :(得分:4)
您可以对当前组使用spread JavaScript ES6(和TypeScript)操作,并将新的group元素添加到数组中:
const onClickGroups = (group: IGroups) => {
const currentGroups = state.searchState.groups;
setState({
...state,
searchState: {
...state.searchState,
groups: [ ...currentGroups, group ]
}
});
};