如何使用获取数组的对象更新 useState 钩子?打字稿

时间:2021-05-10 16:09:21

标签: javascript arrays reactjs typescript react-hooks

嗨,我想用 useState 钩子更新位于对象中的数组中的新值。

这个结构正是我想要的。

{ A : ['aa', 'aaa', 'aaaa', 'aaaaa'],
  B : ['bb', 'bbb', 'bbbbbbb', 'bbbbb'],
  C : ['cc', 'ccc'] }

在我的代码中,A、B、C 是类别,数组中的元素是 keyValue。

这是我的代码

type selectedInterestType = {
  [category: string]: string[];
};

const InterestBtn = ({ category, keyValue }: Props) => {
  const [
    selectedInterest,
    setSelectedInterest,
  ] = useState<selectedInterestType>({});

  const onInterestClick = () => {
    setSelectedInterest({
      ...selectedInterest,
      [category]: [category]
        ? selectedInterest[category].concat(keyValue)
        : [keyValue],
    });
  };
  
  return (
    <button
      onClick={onInterestClick}
      
    >
      <p>{value.kr}</p>
    </button>
  );
};

我正在使用 react 和 typescript。 我不知道如何用对象、数组更新我的 usestate 状态 如果已经有像 'A' 'B' 这样的 'category' 那么添加 keyValue, 但如果为空,则创建 [category] ​​: 'keyvalue'。

从现在开始,“无法读取未定义的属性'concat'”错误

1 个答案:

答案 0 :(得分:1)

我最近使用这样的模式,这是我的代码示例:

setAlbums(prevAlbums => {
  // copy your previous state
  const prevAlbumsCopy = { ...prevAlbums };
  // check if your object alredy has this key 
  if (prevAlbumsCopy[category]) {
    // so with the copy you can use push bcs it's alredy a new reference
    prevAlbumsCopy[category].push(keyValue)
  } else {
    prevAlbumsCopy[category] = [keyValue]
  }

  return prevAlbumsCopy;
});

我只是在示例中使用 Album,但您可以使用您的州名称轻松重构。

这个例子的想法是添加一个函数来更新你的状态,做你想做的一切,比如检查元素是否存在,设置它...

我将对象复制到有不同的引用,因此触发重新渲染。