首页 > 解决方案 > 如何使用获取数组的 Object 更新 useState 挂钩?用打字稿

问题描述

嗨,我想使用 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>
  );
};

我正在使用反应和打字稿。我不知道如何用对象、数组更新我的 usestate 状态,如果已经有 'A' 'B' 之类的 'category' 然后添加 keyValue,但如果它为空,则创建 [category] ​​:'keyvalue'。

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

标签: javascriptarraysreactjstypescriptreact-hooks

解决方案


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

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;
});

我只是在我的例子中使用专辑,但你可以用你的州名轻松重构。

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

我复制我的对象以获得不同的引用,从而触发重新渲染。


推荐阅读