我正在学习React并试图第一次自己做一个小项目,但是我在useEffect
上遇到了麻烦。
我正在尝试使用来自后端的信息自动填充表单。我可以自动填充它,但是它会不断发送GET请求。这就是我所拥有的:
useEffect(() => {
axios
.get('/admin/edit-product' + location.search)
.then((res) => {
const updatedControls = {
...controlsState,
title: {
...controlsState.title,
value: res.data.title,
},
image: {
...controlsState.image,
value: res.data.image,
},
price: {
...controlsState.price,
value: res.data.price,
},
description: {
...controlsState.description,
value: res.data.description,
},
};
setControlsState(updatedControls);
})
.catch((err) => console.error(err));
}, [controlsState, location.search]);
我以为依赖数组应该阻止它连续运行,但是我想我还缺少其他东西。
不确定是否需要它,但这就是我的原始状态:
const [controlsState, setControlsState] = useState({
title: {
elementType: 'input',
elementConfig: {
type: 'text',
},
label: 'Product Title: ',
value: '',
},
image: {
elementType: 'input',
elementConfig: {
type: 'url',
},
label: 'Image URL: ',
value: '',
},
price: {
elementType: 'input',
elementConfig: {
type: 'number',
},
label: 'Price: ',
value: '',
},
description: {
elementType: 'textarea',
elementConfig: {
name: 'description',
htmlFor: 'description',
},
label: 'Description: ',
value: '',
},
});
和location
来自react-router-dom useLocation
答案 0 :(得分:1)
您已将controlsState作为useEffect的依赖项。但是在useEffect内部,您使用的是setControlsState,它会更改controlsState的值。而且,由于您已将controlsState作为依赖项提供,所以useEffect会在其任何依赖项更改时发生。因此,它反复发生
如果您希望useEffect只运行一次,则将[]作为第二个参数:
useEffect(() => {
...your code...
}, [])