![](/img/trans.png)
[英]How to create a string array in the useState hook and update that same array in TypeScript?
[英]How to update useState hook with Object which gets an array? with typescript
嗨,我想使用 useState 挂钩更新位于 object 的数组中的新值。
这个结构就是我想要的。
{ 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> ); };
我正在使用反应和 typescript。 我不知道如何用 object 更新我的 usestate state,如果已经有 'A' 'B' 之类的 'category' 则添加 keyValue,但如果它为空,则创建 [category]: 'keyvalue'。
从现在开始,发生“无法读取未定义的属性 'concat'”错误
我最近使用这样的模式,这是我的代码示例:
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;
});
我只是在我的示例中使用专辑,但您可以使用 state 名称轻松重构。
这个例子的想法是添加一个 function 来更新你的 state 做你想做的一切,比如检查元素是否存在,设置它......
我复制我的 object 以获得不同的引用,从而触发重新渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.