避免子组件更新父状态时父组件重新渲染,

发布于 2025-01-20 14:45:41 字数 1551 浏览 0 评论 0原文

在我们的React应用程序中,我们有亲子成分。儿童组件调用父方法以更新父状态值。这是示例代码

// parent component

const parent = ({ items }) => {
    const [information, setInformation] = useState([]);
    const updateParentInformation = (childUpdate) => {
         setInformation(information + childUpdates)
    }
    return (
        <div>
            <div>{information}</div>
            ...
            {items.map((item) => {
                return (
                    <ChildComponent item={item} updateParentInformation={updateParentInformation} />
            )})}
        </div>
    )
}

// Child Component,

const ChildComponent = ({ item, updateParentInformation }) => {
    useEffect(() => {
        const cardInformation = calculateCardInformation(item)
        updateParentInformation(cardAmpScripts)
     }, [item])
    return (
        <div>
            .....
        </div>
    )
}

因此Child Component调用父级的updateParentInformation函数以更新父个状态,然后重新呈现父级的组件。我在这里有几个问题

  1. 在某些情况下,我们可能有100-150个儿童组件,在这种情况下,我们的父母会重新渲染很多,如何避免这种情况。我们可以避免此代码

     ...。
     让回收updates = 0
     const updateParentInformation =(childUpdate)=&gt; {
          收到updates ++
          if(接收到== items.length {
              setInformation(信息 + childupdates)
          }
     }
     

如果这是一种可能的方式,

  1. ,那么我有问题2如何避免儿童组件调用父母的updateParentInformation。例如,Child 1称为UpdateParentInformation函数,同时Child 2也称为UpdateParentInformation,在这种情况下,我们可能会失去一个孩子的更新。

In our react application, We have parent-child component. Child component calls parent method to update parent state values. Here is sample code

//Parent component

const parent = ({ items }) => {
    const [information, setInformation] = useState([]);
    const updateParentInformation = (childUpdate) => {
         setInformation(information + childUpdates)
    }
    return (
        <div>
            <div>{information}</div>
            ...
            {items.map((item) => {
                return (
                    <ChildComponent item={item} updateParentInformation={updateParentInformation} />
            )})}
        </div>
    )
}

//Child Component

const ChildComponent = ({ item, updateParentInformation }) => {
    useEffect(() => {
        const cardInformation = calculateCardInformation(item)
        updateParentInformation(cardAmpScripts)
     }, [item])
    return (
        <div>
            .....
        </div>
    )
}

So child component calls the parent's updateParentInformation function to update the parent state, which re-renders parent components. I have a few questions here

  1. In some cases, we may have 100-150 Child components, in such cases our parents will re-render a lot, How to avoid this. We can avoid this throgh this code

    ....
     let recievedUpdates = 0
     const updateParentInformation = (childUpdate) => {
          recievedUpdates++
          if(recievedUpdates == items.length {
              setInformation(information + childUpdates)
          }
     }
    

If this is a possible solition then I have question 2

  1. How to avoid race-condition when child component calls parent's updateParentInformation. For example child 1 is called updateParentInformation function and at the same time child 2 is also called updateParentInformation, in this case we may lose updates from one child.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何时共饮酒 2025-01-27 14:45:41

不能避免这种情况,因为如果组件的内部状态发生变化,它总是必须重新渲染。因此,在这种情况下,您有两种可能的方法来解决性能问题:

  1. 将您的子级包裹在 React.memo() 中,这样每次您的子级之一更新父级组件中的状态时,所有子级都会更新不关心并且不接收更新的状态作为道具,不会重新渲染。
  2. 使用全局状态管理器(建议)。如果您有数百个使用通用状态的组件,并且可能通过 props 钻取这些状态,导致大量不必要的重新渲染,那么您肯定会受益于状态管理器,例如 Redux,这样只有使用特定状态切片的组件才会在状态更改时重新渲染。

无论如何,如果在树顶部的组件(父级)中执行繁重的计算,请始终将它们包装在 useMemo() 钩子中,函数和 useCallback( ),这样您就能够解决大部分性能问题。

关于race-condition的问题,react useState可以与这样的回调一起使用,以确保它执行时能够访问到最新的- 该时刻该状态的日期值:

const [state, setState] = useState(0)
setState(currentState => currentState + 1)

You CAN'T avoid that since a Component always has to re-render if its internal state changes. So you have two possible approaches to solve performance issues in this scenario:

  1. Wrap your children in React.memo(), this way every time one of your children updates a state in the Parent component, all the children that don't care and don't receive that updated state as a prop, won't re-render.
  2. Use a global state manager ( Suggested ). If you have hundreds of components that use common states, and maybe those states are drilled through props, causing a lot of unnecessary re-renders, you will definitely get advantage of a State Manager, like Redux, this way only the components that use a particular slice of the state will re-render when that state changes.

In any case, if in your Components that are on top of the Tree, ( Parents ) you perform heavy calculations, always wrap them in useMemo() hooks, same goes with functions and useCallback(), this way you will be able to address most of your performance issues.

Regarding the question about race-condition, react useState can be used with a callback like this, to be sure that when it executes it will have access to the most up-to-date value of that state in that moment:

const [state, setState] = useState(0)
setState(currentState => currentState + 1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文