【发布时间】:2022-02-03 16:31:25
【问题描述】:
我有一个对象列表。一旦对象的位置字段发生更改,我想进行 api 调用。所以为此,我有一个 useEffect,它有 id、index 和 location 作为它的依赖项。我已经为位置设置了一个空检查,如果位置不为空,我想进行 api 调用。但问题是,即使位置为空,api 也会被调用,我最终得到 400。我该如何解决这个问题并在位置不为空时进行调用?
const [plants, setPlants] = useState([
{
name: 'Plant 1',
id: uuidv4(),
location: '',
coords: {},
country: '',
isOffshore: false,
}
]);
const [locationIDObject, setlocationIDObject] = useState({
id: plants[0].id,
index: 0
});
const handlePlantLocChange = (id, index, value) => {
setPlants(
plants.map(plant =>
plant.id === id
? {...plant, location: value}
: plant
)
)
setlocationIDObject({
id: id,
index: index
})
}
const getCoords = (id, index) => {
axios.get('http://localhost:3002/api/coords', {
params: {
locAddress: plants[index].location
}
}).then((response) => {
if(response.status === 200) {
handlePlantInfoChange(id, PlantInfo.COORD, response.data)
}
})
}
const handler = useCallback(debounce(getCoords, 5000), []);
useDeepCompareEffect(() => {
if(plants[locationIDObject.index].location !== '')
handler(locationIDObject.id, locationIDObject.index);
}, [ locationIDObject, plants[locationIDObject.index].location])
return (
<div className='plant-inps-wrapper'>
{
plants.map((item, idx) => {
return (
<div key={item.id} className="org-input-wrapper">
<input placeholder={`${item.isOffshore ? 'Offshore' : 'Plant ' + (idx+1) + ' location'}`} onChange={(e) => handlePlantLocChange(item.id, idx, e.target.value)} value={item.isOffshore ? 'Offshore' : item.location} className="org-input smaller-input"/>
</div>
)
})
}
</div>
)
【问题讨论】:
-
你的空检查应该直接在
axios.get之前(即它应该在getCoords之内)。另外,!== ''与空检查不一样。 -
是的,我的错。我有时使用 null 检查来指代字符串何时为空,我应该改掉这个坏习惯。
标签: reactjs use-effect