useEffect 连续触发 GET 请求
useEffect continuously fires GET requests
我正在学习 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
您已将 controlsState 作为 useEffect 的依赖项。但是在 useEffect 中,您使用的是 setControlsState,它会更改 controlsState 的值。并且由于您已将 controlsState 作为依赖项提供,因此每次其依赖项发生更改时都会发生 useEffect。因此它反复发生
如果你想让useEffect只运行一次,给[]作为第二个参数:
useEffect(() => {
...your code...
}, [])
我正在学习 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
您已将 controlsState 作为 useEffect 的依赖项。但是在 useEffect 中,您使用的是 setControlsState,它会更改 controlsState 的值。并且由于您已将 controlsState 作为依赖项提供,因此每次其依赖项发生更改时都会发生 useEffect。因此它反复发生
如果你想让useEffect只运行一次,给[]作为第二个参数:
useEffect(() => {
...your code...
}, [])