javascript - 如何使用获取数组的 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'”错误
解决方案
我最近使用这样的模式,这是我的代码示例:
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;
});
我只是在我的例子中使用专辑,但你可以用你的州名轻松重构。
这个例子的想法是添加一个函数来更新你的状态,做你想做的一切,比如检查元素是否存在,设置它......
我复制我的对象以获得不同的引用,从而触发重新渲染。
推荐阅读
- apache-kafka - 如何在 Spring webflux 和 Kafka 中创建 Bulk 消费者
- javascript - Chrome onbeforeunload 事件不会创建确认模式
- string - 从 hive 中的字符串值计算季度
- r - 更快地选择随机列值
- reactjs - Reactjs useMemo 钩子行为,如 componentDidMount
- python - 如何在此代码中使用数据框执行 if 语句?
- python - Numpy 向量/矩阵乘法意外工作
- django - Django 基于类的视图返回 HttpResponse 如 HttpResponseBadRequest
- javascript - 如何在 React 中为 JSON 数据表创建搜索过滤器?
- python - 通过 div/span 格式的 xpath 查找/定位可点击文本