第二次进入后的onChange效果
onChange effect after second entry
我对 ReactJS 有点陌生,我的 onChange
函数有问题,它在第二次输入后开始显示,每次都晚一个字母。我显然不明白为什么
这是我的代码:
const [values, setValues] = useState({
latinName: "",
wingLength: "",
weight: "",
adiposity: "",
age: "",
howCaptured: "",
whenCaptured: "",
whereCaptured: "",
ringNumber: "",
takeover: "",
});
const handleChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
console.log(values);
}
<input type="text" name="latinName" id="latinName" onChange={handleChange} value={values.latinName} />
Here my input
Here my result
useState
钩子的 setState
有效 async
。因此,在状态更新期间,您仍然同时获得之前的值。
您可以在您的案例中使用 useEffect
挂钩。
useEffect(() => console.log(values), [values]);
完整代码:
import { useEffect, useState } from "react";
export default function App() {
const [values, setValues] = useState({
latinName: "",
wingLength: "",
weight: "",
adiposity: "",
age: "",
howCaptured: "",
whenCaptured: "",
whereCaptured: "",
ringNumber: "",
takeover: ""
});
useEffect(() => console.log(values), [values]);
const handleChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value
});
};
return (
<input
type="text"
name="latinName"
id="latinName"
onChange={handleChange}
value={values.latinName}
/>
);
}
我对 ReactJS 有点陌生,我的 onChange
函数有问题,它在第二次输入后开始显示,每次都晚一个字母。我显然不明白为什么
这是我的代码:
const [values, setValues] = useState({
latinName: "",
wingLength: "",
weight: "",
adiposity: "",
age: "",
howCaptured: "",
whenCaptured: "",
whereCaptured: "",
ringNumber: "",
takeover: "",
});
const handleChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
console.log(values);
}
<input type="text" name="latinName" id="latinName" onChange={handleChange} value={values.latinName} />
Here my input
Here my result
useState
钩子的 setState
有效 async
。因此,在状态更新期间,您仍然同时获得之前的值。
您可以在您的案例中使用 useEffect
挂钩。
useEffect(() => console.log(values), [values]);
完整代码:
import { useEffect, useState } from "react";
export default function App() {
const [values, setValues] = useState({
latinName: "",
wingLength: "",
weight: "",
adiposity: "",
age: "",
howCaptured: "",
whenCaptured: "",
whereCaptured: "",
ringNumber: "",
takeover: ""
});
useEffect(() => console.log(values), [values]);
const handleChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value
});
};
return (
<input
type="text"
name="latinName"
id="latinName"
onChange={handleChange}
value={values.latinName}
/>
);
}