我使用运行附近的搜索,然后进行详细搜索,以获取每个返回位置的小时数据。当我进行附近的搜索时,我收集所有的placeIds并将它们作为支柱传递给我运行详细搜索的组件。我使用useEffect ReactJs钩子对我的nodeJs和Express后端进行了一个提取调用,并在该获取调用的正文中发送位置Ids。我循环遍历所有的ID,并将每个ID的API调用添加到后端的承诺数组中,然后将结果发送回前端。
这完全适合我所需要的东西。问题是,我通过将useEffect作为依赖项传递给useEffect钩子,从而调用placeId支柱值更改上的props.placeIds。在useEffect钩子中有一个依赖项使API调用在用户运行应用程序时持续运行。这再加上每个调用中都有15+ I,使得应用程序每分钟运行数千次API调用,我认为这在生产中会花费很大的代价。
我知道,如果我将一个空白数组传递给useEffect钩子,它将只运行一次。问题是,当我这样做时,useEffect API调用在它获得任何placeIds之前运行,该placeIds会使应用程序崩溃。
如何使useEffect API调用等待props.placeIds更改,然后只运行一次?
以下是我对后端的JSX提取调用:
useEffect(() => {
fetch('/api/place-details-search', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
placesId: props.placeIds,
dayNumVal: props.dayNumVal,
numOfPlaces: props.placeIds.length,
})
}).then(response => response.json()).then(data => {
setPlaceHours(data.placeHourText)
})
}, [props.placeIds])下面是我的nodeJS和express代码,它遍历数据并将其发送回前端:
app.post('/api/place-details-search', (req, res) => {
const dayNumVal = req.body.dayNumVal
const numOfPlaces = req.body.numOfPlaces
const placeIds = req.body.placeId
let placeHourText = [];
let placeHourName = [];
let promises = [];
let parsedDayNumVal
if (dayNumVal == 0) {
parsedDayNumVal = 6
} else {
parsedDayNumVal = dayNumVal - 1
}
for (var i = 0; i < numOfPlaces; i++) {
promises.push(
axios.get('https://maps.googleapis.com/maps/api/place/details/json?place_id=' + placeIds[i] + '&fields=name%2Copening_hours&key=' + process.env.REACT_APP_GOOGLE_MAPS_API_KEY).then(response => {
if (response.data.result !== undefined) {
placeHourText.push(response.data.result.opening_hours.weekday_text[parsedDayNumVal]);
}
if (response.data.result !== undefined) {
placeHourName.push(response.data.result.name)
}
})
)
}
Promise.all(promises).then(() => {
const placeHourTextTwo = []
for (var i = 0; i < placeHourText.length; i++) {
let parsedPlaceHourText = placeHourText[i]
parsedPlaceHourText = parsedPlaceHourText.split("y").pop()
placeHourTextTwo.push([placeHourName[i], parsedPlaceHourText])
}
res.send({ placeHourText: placeHourTextTwo })
});
});发布于 2022-08-31 19:38:42
将[props.placeIds]作为useEffect()的依赖项意味着:
props.placeIds 更改,,否则请不要运行
因此,如果您的setPlaceHours(data.placeHourText)函数更新了props.placeIds,那么它是不同的无限循环情况。
一个可能的解决方案是传递从placeIds派生的另一个支柱,但是它不会在每个API调用中更新
https://stackoverflow.com/questions/73560702
复制相似问题