什么时候反应完全重新渲染组件

时间:2020-05-02 18:07:53

标签: reactjs state render react-props

我在Internet上找到了“反应组件在状态或道具发生变化时会自动重新渲染”的内容,但是如果在道具中传递的状态与状态不同,即使该道具无法触发渲染,道具随时间改变了。

在这段代码中,我通过了一个不使用状态的道具

父母

import React from "react";
import Child from "./child";

export default function Parent() {
  let count = 0;

  setInterval(() => {
    count++;
    console.log(count);
  }, 1000);

  return <Child count={count} />;
}

孩子

import React from "react";

export default function Child(props) {
  console.log("render from child");        //console.log once

  return <h1>{props.count}</h1>;
}

感谢您帮助我解决这个混乱的问题

1 个答案:

答案 0 :(得分:1)

几天前,我正在教一个初级的地雷记忆反应,后来我想出了一种描述性的方法来演示重新渲染的工作原理。

让我们创建一个计数器组件


const Counter = () => {

const [count, setCount] = React.useState(0)


const increment = () => setCount(count +1)

console.log("render from counter")

return (
      <>
          <h1> Counter: {count} </h1>
          <button onClick={increment}>Add count</button>
     </>

}

所以基本上,我有一个计数器组件,每次单击按钮时,它都会增加计数。

但还要注意那里的控制台日志。每次我单击按钮时,它将更改状态,使组件重新呈现,从而执行console.log函数。

现在我们知道,只要状态发生变化,组件就会重新呈现,但是道具的更改也可以重新呈现。

让我告诉你我的意思。


const Counter = () => {

const [count, setCount] = React.useState(0)


const increment = () => setCount(count +1)

console.log("render from counter")

return (
      <>
          <h1> Counter: {count} </h1>
          <button onClick={increment}>Add count</button>
         <ChildCounter count={count} />
     </>

}


// Child component
const ChildCounter = ({count}) => {

console.log("render from child")

return (
      <>
          <h1> our counter is now at : {count} </h1>
     </>

}

在这里,我有另一个组件是counter组件的子组件。我将count作为子组件的支持。

每次计数在父组件(即Counter)中更改时,子组件将重新呈现。

那是因为两件事。一是道具已更改,其二是因为父组件在重新渲染时会强制其子对象重新渲染。

现在您看到,状态发生变化,道具发生变化和父项发生变化时,会发生反应中的重新渲染。

我们可以使用记忆功能阻止孩子进行不必要的渲染,在这里我不会谈论。

我希望这会有所帮助。

请原谅我缺乏缩进和难看的外观*代码。

相关问题