【问题标题】:I am confused as to how my dependencies change every render?我对我的依赖项如何改变每个渲染感到困惑?
【发布时间】:2021-01-25 18:33:20
【问题描述】:
   // 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 作为依赖项将导致每次 restaurantIndexes 更新时运行效果,这发生在效果内部(导致无限循环)。
  • 顺便说一句,你的效果简化为setRestaurantIndexes(Object.keys(yelpResults))
  • 谢谢,这是有道理的!制作一个临时数组以使其不可变不是最佳做法吗?我不确定我是否理解正确,但这是我在学习时在视频中看到的内容
  • JS 中的数组是可变的,使用 push 方法改变数组。您还使用了let 关键字,而是使用const,所以它只是初始化。你应该真正关心的是改变yelpResults,而你没有。
  • 另外(除非此示例已被简化),restaurantIndexes 是派生状态。这意味着您始终可以根据其他一些数据(在本例中为 yelpResults)找出它应该是什么。您可能应该用const restaurantIndexes = Object.keys(yelpResults); 替换此效果和状态

标签: reactjs


【解决方案1】:

我认为你做错了什么是当这些值之一改变时你正在重新渲染东西[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]);

【讨论】:

  • 检查依赖项是否已更改是 useEffect api 的确切职责(并且对一般更新做出反应)。除非您需要使用不同的比较实现,否则这总是一个错误。此外,数组是 JavaScript 中的对象(引用类型),因此相等比较不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
相关资源
最近更新 更多