[英]warning in ReactJS. A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to
[英]Changing input of controlled component changes property value to undefined
我在 useState 中有一組默認值。 在通過 select 發生 onChange 事件時,數組中的屬性更改為未定義。 我一直在閱讀受控組件,我認為我錯過了一些愚蠢的東西。
const [config, setConfig] = useState([{
carType: "Sedan",
carColor: "Red"
}]);
// onChange
const setCarType = (e) => {
setConfig({ ...config[0], carType: e.target.value });
};
const { carType, carColor } = config[0];
我認為我可以在這里使用擴展運算符,以便將 config[0] 的兩個屬性復制到兩個單獨的常量中。 我最初在 object 中有配置,但被拋出錯誤“對象作為反應子無效”。
const setCarType = (e) => {
setConfig([{ ...config[0], carType: e.target.value }]);
};
const setCarColor = (e) => {
setConfig([{ ...config[0], carColor: e.target.value }]);
};
當您設置配置時,您將新的 object 設置為配置,但它被初始化為對象數組。 所以 config[0] 是未定義的,因為 config 不再是一個數組。 試試上面的代碼,問題就解決了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.