0

不确定为什么每次 onChange 运行时的状态值都等于初始状态值。这意味着当我更改附加了此 onChange 的组件的值时,只有它的值被设置,其余的都未设置,因为这就是它们的初始值。使用的框架是nextJS。

import { useState, ChangeEvent } from 'react';
import { IInitialState } from '../types';

const INITIAL_STATE: IInitialState = {
  companySize: '',
  salesChannel: '',
  brandWebsite: '',
  customersCatered: '',
  productCategories: [],
};

type FieldType = keyof IInitialState;

export function useMyCustomHook() {
  const [state, setState] = useState<IInitialState>(INITIAL_STATE);
  console.log('run');

  function onChange(
    selectedItem: string,
    field: FieldType,
    data?: Array<number>
  ) {
    const value = selectedItem;
    let newState: IInitialState;
    if (field !== 'productCategories') {
      console.log(state, { ...state });
      newState = { ...state, [field]: value };
    } else {
      if (!data) {
        console.log('here');
        return;
      }
      newState = { ...state, [field]: data };
    }
    console.log(field, selectedItem, newState);
    setState(newState);
  }

  function removeSelectedCategory(productId: number | string) {
    const newProductCategoriesList = state.productCategories.filter(
      item => item != productId
    );
    setState({ ...state, productCategories: newProductCategoriesList });
  }

  return {
    state,
    onChange,
    removeSelectedCategory,
  };
}
4

0 回答 0