简体   繁体   English

当 object 已加载从 API 更新时,重新渲染 UseEffect 的最佳方法

[英]Best way to have UseEffect re-render when an object has loaded updated from an API

I was wondering what the best practice for handling this situation is.我想知道处理这种情况的最佳做法是什么。

Currently I am getting data back from an api in this format:目前我正在从 api 以这种格式取回数据:

department: { 
    workers: {}
}

The workers field gets populated with a bunch of key:value pairs in the format like this: workers 字段填充了一堆键:值对,格式如下:

workers: {
   workerId: {...},
   workerId: {...},
   workerId: {...}
  .... and so on (workerId is a unique Id and will have data on the worker)
}
function Department(props){
     const {workers} = useSelector(({company}) => company.department)

     useEffect(() => {

        This is where I am wondering what I need to do.

        "workers" is initially = {}. But when it eventually gets populated with 
        the many "workerId" properties, there is no re-render.

     }, [workers])

}

This happens because React can't predict the Value Changed inside the particular object(workers) in terms of its key value pairs.发生这种情况是因为 React 无法根据其键值对预测特定对象(workers)内部的 Value Changed。 Objects are always shallow compared to their previous state and the address of the object remains same even when object was {} or loaded with data from API.与之前的 state 相比,对象总是很浅,即使 object 是 {} 或加载了来自 ZDA16474238708ACA3 的数据,object 的地址也保持不变。

When using workers object as a dependency array in useEffect hook, It does not detects change in its data as the address of the workers object remains same and it takes it same as the previous state and hence the component does not re-renders.当使用工人 object 作为 useEffect 挂钩中的依赖数组时,它不会检测到其数据的变化,因为工人 object 的地址保持不变,它与之前的 Z9ED39E2EA931586B6A985A6942EF573E 相同,因此组件不会。

The only way to cause a re-render is to set state.导致重新渲染的唯一方法是设置 state。 Mutating an object during a useEffect will not cause a re-render.在 useEffect 期间改变 object 不会导致重新渲染。 So you could fix this by adding a state variable, and then setting state once you've received the data from API.因此,您可以通过添加 state 变量来解决此问题,然后在收到来自 API 的数据后设置 state。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM