如何使用Typescript向状态添加新值



您需要向数组添加新值,我不明白问题出在哪里。当你点击一个复选框时,你需要获得这个复选框的id,并将其写入相应问题的答案数组中

type Result = number;
interface Answer {
result: Result[];
}
const answers: Answer[] = [];
questions.forEach(() => {
answers.push({
result: [],
});
});
const [currentAnswer, setNewAnswer] = useState<Answer[]>(answers)
const handleChange = (e:React.ChangeEvent<HTMLInputElement>) =>{
// console.log(typeof(currentAnswer),currentAnswer);
if(e.target.checked){
console.log(currentAnswer[currentQuestion].result.push(Number(e.target.id)));
setNewAnswer(
currentAnswer[currentQuestion].result.push(Number(e.target.id) // ERROR HERE
)         
...

我收到错误

const currentAnswer: Answer[]
// Argument of type 'number' is not assignable to parameter of type 'SetStateAction<Answer[]>'

在这种情况下应该使用.concat()来返回新的数组

.push()将只返回新的长度,该长度是数字并且与您创建的类型不兼容。

setNewAnswer(
currentAnswer[currentQuestion].result.concat(Number(e.target.id)) // ERROR HERE
)

为了扩展Mic Fung的答案,push对现有数组进行了变异,并且不返回新数组。

const myArray = [1, 2, 3]
myArray.push(4) // returns 4, which is the new array length
console.log(myArray) // [1, 2, 3, 4]

concat不会改变现有的数组,而是返回一个新的数组

const myArray = [1, 2, 3]
const myNewArray = myArray.concat(4)
console.log(myNewArray) // [1, 2, 3, 4]
console.log(myArray) // [1, 2, 3]

使用React时,应避免直接更改状态。相反,创建新值并将其传递给setState函数。这就是为什么像concat这样的功能比像push这样的功能更受欢迎,因为它们可以避免突变。

最新更新