reactjs - How can I add an element to a list with a key value using a useState Record type in React typescript?
问题描述
The structure of my Record type looks like this:
const PEOPLE_MAP_INIT: Record<string, Person[]> = {
"1": [],
"2": [],
"3": []
};
The useState is initialized like this:
const [PEOPLE_MAP, SET_PEOPLE_MAP] = useState<Record<string, Person[]>>(PEOPLE_MAP_INIT);
Basically, I am trying to hold a list of "Person objects" corresponding to the string key value which will each hold its own unique list.
I'm trying to add a Person object to the first list in the PEOPLE_MAP from a given master list of Person objects:
SET_PEOPLE_MAP({...PEOPLE_MAP, ["1"]: personList[i]});
However, this just gives me type errors. I know somewhere I'm misunderstanding the use of Record types but I'm just not sure how to go about fixing this.
解决方案
I wrote the AddPerson function like this and it works fine without any error type
const addPerson = () => {
const newPerson = new Person('Joe', 30);
const newPeopleMap = {...peopleMap};
newPeopleMap["1"].push(newPerson);
setPeopleMap(newPeopleMap);
};
The whole code is here -> https://codesandbox.io/s/practical-wind-8spnv
推荐阅读
- react-native - 如何从 React-Native 中的 API 获取对象数据中的对象
- r - 按列中的计数拆分行
- docker - 如何在不杀死容器的情况下将自定义 NAR 添加到正在运行的 Docker Nifi?
- php - 从php中的对象数组中获取所有最大值
- node.js - 将元字段添加到产品 shopify
- apache-spark-sql - 为什么即使合并没有更新任何内容,Databricks Delta 也会复制未修改的行?
- javascript - 如何从 REST API 获取响应并从 jquery ajax 调用执行操作?
- python - 无法将自定义模型保存为 .pb 格式(tensorflow 2.1.0)
- python - 如何在python中迭代字典的前n个元素?
- c++ - 重新分配时的指针仍指向旧值