![](/img/trans.png)
[英]How can i add a property to an inner Object in Typescript with spread operator?
[英]How can the index of an object within an array be preserved when modifying an object property while using the spread operator?
我有一个 React useState-Variable,它存储一个属于这种问题类型的对象数组:
type Question = {
id: number,
text: string,
otherProps: string,
...... (and so on)
}
我的 useState 示例
const [questions, setQuestions] = React.useState<Question[]>([{id: 1, text: "hello?", otherProps: "Lorem Ipsum"}])
这些 Question 对象在 useState-Variable Array 中的顺序很重要,所以我的问题是:如何更改以下 function 以便更改 Question 的文本,但维护/保留修改后的 object 的数组索引? 我知道目前我首先删除 object 然后在最后放置一个新创建的,但我现在想不出另一种方法。
function setQuestionTextById(id:number, text:string) {
if (!questions) return;
const question:Question|undefined = questions.find(x => x.id === id);
if (!question) return;
const newQuestion: Question = {
...question,
text,
};
const filteredQuestions = questions.filter(item => item.id !== id);
setQuestions([...filteredQuestions, newQuestion]);
}
你应该在数组上使用map
和 function 检查id
是否是你想要的 - 如果是它用新text
修改它,否则保持原样。
这样,你的整个 function 就变成了:
function setQuestionTextById(id:number, text:string) {
const updatedQuestions = questions.map(question => question.id === id ? { ...question, text } : question);
setQuestions(updatedQuestions);
}
我发现它比原来的更具可读性,并且可以根据您的需要保留顺序。
进一步的改进是使用setQuestions
的功能更新形式,因此它不依赖于questions
的先前值,但我会把它留给你 - 这可能无关紧要,具体取决于它在你的成分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.