export default function CitySearch() {
const defaultCity = "London";
const [city, setCity] = useState(defaultCity);
const address = useSelector((state) => state?.cityDetails?.city);
const classes = useStyles();
const handleOnChange = (e) => {
setCity(e.target.value);
};
const handleOnBlur = () => {
if (city) setCity(city);
else if (address) setCity(address);
else setCity(defaultCity);
};
useEffect(() => {
setCity((prevState) => address);
}, [address]);
return (
<Box className={classes.root}>
<TextField
label="City"
variant="outlined"
value={city}
onChange={handleOnChange}
onBlur={handleOnBlur}
/>
</Box>
);
}
代码工作正常,但在控制台上抛出此错误“警告:组件正在更改要控制的非受控输入。这可能是由于值从未定义更改为已定义值引起的,这不应该发生。决定使用受控还是在组件的生命周期内不受控制的输入元素。”
但是当我注释掉 useEffect 中的代码时,错误就消失了