我很困惑,我的依赖关系是如何在每次渲染时都发生变化的


// We are only running this at initial render and anytime
// yelpResults gets updated (only once per food and location submit)
useEffect(() => {
// Creating a temp array so our restaurantIndexes is immutable
let tempArray = [];
// Concatenating the value of each index into our state
Object.keys(yelpResults).map((index) =>  tempArray.push(index));

// Saving the results of our restaurant indexes
setRestaurantIndexes(tempArray);
}, [yelpResults, restaurantIndexes]);

警告:超过了最大更新深度。当组件在useEffect内部调用setState时,可能会发生这种情况,但useEffect没有依赖项数组,或者每次渲染时都会更改其中一个依赖项。

我认为您做错的是,当其中一个值更改[yelpResults, restaurantIndexes]时,您正在重新渲染内容,因为useEffect在值更改时会再次渲染。因此,一个更好的解决方案是放置一个if语句,该语句将检查值是否已更改。

const [restaurantIndexes, setRestaurantIndexes] = useState("")
useEffect(() => {
// Creating a temp array so our restaurantIndexes is immutable
let tempArray = [];
// Concatenating the value of each index into our state
Object.keys(yelpResults).map((index) =>  tempArray.push(index));

console.log(tempArray);
//Check if tempArray has changed
if(restaurantIndexes !== tempArray) return
// Set the RestaurantIndex state
setRestaurantIndexes(tempArray);

}, [yelpResults,restaurantIndexes]);

最新更新