我正在学习一些 Reactjs 类(class),并遇到了本类(class)中似乎没有出现的问题。
Customer.js:
import React, { useState } from "react";
const Customer = () => {
const [customerState, setCustomerState] = useState(
{
names: ['Martin', 'Andrea', 'Carol'],
pickedName: 'Martin'
}
);
const switchName = () => {
const namePool = customerState.names;
const number = Math.floor(Math.random()*3); //losowanie liczby w zakresie 0-2
setCustomerState({pickedName: namePool[number]});
}
return(
<div>
<h2>Customer:</h2>
<h3>{customerState.pickedName}</h3>
<button onClick={switchName}>Change name</button>
</div>
);
}
export default Customer;
提到的代码给了我行 setCustomerState({pickedName: namePool[number]});
:
最佳答案
您在更新状态时忘记了 names
字段。只需使用例如包含它即可对象解构。
setCustomerState((prevState) => ({
...prevState,
pickedName: namePool[number],
}));
您的应用程序在 namePool[number]
行中崩溃,因为 namePool
(customerState.names
) 未定义 .
const Customer = () => {
const [customerState, setCustomerState] = useState({
names: ['Martin', 'Andrea', 'Carol'],
pickedName: 'Martin',
});
const switchName = () => {
const namePool = customerState.names;
const number = Math.floor(Math.random() * 3);
setCustomerState((prevState) => ({
...prevState,
pickedName: namePool[number] as string,
}));
};
return (
<div>
<h2>Customer:</h2>
<h3>{customerState.pickedName}</h3>
<button onClick={switchName}>Change name</button>
</div>
);
};
关于javascript - Reactjs - 参数类型不可分配给参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74206357/