简体   繁体   English

React JS 重新渲染

[英]React JS re-rendering

When a component re-renders as a result of calling the state setter function returned by useState, does the entire function component get called again or only parts of the function component get called?当组件由于调用 useState 返回的状态设置器函数而重新渲染时,是再次调用整个函数组件还是仅调用部分函数组件?

function MyComponent() {
  let [count, setCount] = useState(0);
  
  const handleChange = () {
    setCount((prevCount) => prevCount+1)
  }

  return (
    <p onClick={handleChange}>
      Count = {count}
    </p>
  )
}

In the above example, when we click the paragraph element, handleChange() gets called which in turn calls the state setter function setCount() .在上面的例子中,当我们点击段落元素时, handleChange()被调用,它又调用状态设置器函数setCount() This causes our component to re-render.这会导致我们的组件重新渲染。 But when the component re-renders( or the function MyComponent gets called), the useState(0) function gets called again.但是当组件重新渲染(或函数 MyComponent 被调用)时, useState(0)函数被再次调用。 This should set the initial value of count to 0 again.这应该将count的初始值再次设置为 0。 So shouldn't the counter be stuck at 0 instead of progressing to 1, 2, 3 and so on?那么计数器不应该停留在0而不是前进到1、2、3等等吗?

Let say your component tree has parent and has children called childOne and childtwo.假设您的组件树有父级,并且有名为 childOne 和 childtwo 的子级。 if you change the state of the ChildOne;Only the ChildOne get rendered, Not Parent and childtwo get rendered.如果您更改 ChildOne 的状态;只有 ChildOne 被渲染,Not Parent 和 childtwo 被渲染。 But if you change the state of the parent, whole component tree get retendered但是如果你改变父级的状态,整个组件树都会重新渲染

Whole functional component will be rerendered.整个功能组件将被重新渲染。 If the props value which you are passing to the child component is not changing then you can prevent the rerendering of child component by using React.memo如果你传递给子组件的 props 值没有改变,那么你可以通过使用 React.memo 来防止子组件的重新渲染

This is the idea of hooks.这就是钩子的想法。 They use closures .他们使用闭包

If it was let count = 0 , then yes, if would reset to 0, this is why it is let [count] = useState(0)如果它是let count = 0 ,那么是的,如果会重置为 0,这就是为什么它是let [count] = useState(0)

The whole thing gets re-render and everything is getting re-calculated.整个事情被重新渲染,一切都被重新计算。

The argument you pass in useState / useRef is used only once, when the component mounts.您在 useState / useRef 中传递的参数仅在组件挂载时使用一次。 If it is expensive operation, it recalculate on each render (there are ways to improve this), but the value of it is used only once.如果是昂贵的操作,它会在每次渲染时重新计算(有办法改进),但它的值只使用一次。 Then when you call setState it updates the value.然后,当您调用 setState 时,它​​会更新该值。

They work like this:他们是这样工作的:

let ref = {};

const useRef = (defaultValue) => {
 if (!ref.current) {
    ref.current = defaultValue
 }
 return ref
}

The hook argument is used only once.钩子参数只使用一次。

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

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