我希望能够将输入表单重新用作编辑表单,因此在表单组件中,我使用{useParams}检查网址中是否有 id ,如果存在,设置输入字段的状态以及我从随道具传递的函数 getContact 中获得的数据。
在UseEffect中,我要跟踪 id ,而不是 props ,因此我只是将 [id] 作为依赖项放在useEffect的末尾。如果添加 [id,props] ,我将无法设置输入字段的状态,因为它会立即将其设置回我从 getContact()返回的值>(因为要进行编辑,因此有一个 id )。
我对React还是很陌生,所以我只是想知道是否有更好的方法可以做到这一点,还是应该在代码中加入 // eslint-disable-next-line 继续我的生活:-)
const Form = (props) => {
const { id } = useParams();
const [input, setInput] = useState({});
useEffect(() => {
setInput(id ? props.getContact(id) : {});
}, [id]);
const handleChange = (event) => {
let value = event.target.value;
let name = event.target.name;
setInput((prev) => {
return { ...prev, [name]: value };
});
};
... A few more functions and then a return that spits out som JSX
答案 0 :(得分:1)
useEffect中使用的所有内容都应添加到依赖项数组中。为什么不提取要设置的ID呢?
const contectId = id ? props.getContact(id) : {};
useEffect(() => {
setInput(contectId);
}, [contectId]);
仅当将{}存储在渲染时不会改变的位置时,此方法才有效: 像这样:
const emptyArray = React.useMemo(() => {}, [])
const contectId = id ? props.getContact(id) : emptyArray;
useEffect(() => {
setInput(contectId);
}, [contectId]);
或
const emtyArray = {};
const Form = (props) => {
const { id } = useParams();
const [input, setInput] = useState({});
const contectId = id ? props.getContact(id) : emtyArray;
useEffect(() => {
setInput(contectId);
}, [contectId]);
const handleChange = (event) => {
let value = event.target.value;
let name = event.target.name;
setInput((prev) => {
return { ...prev, [name]: value };
});
console.log(input);
};