【问题标题】:In React, why doesn't changing non-state props prompt rerenders? [duplicate]在 React 中,为什么更改非状态道具不提示重新渲染? [复制]
【发布时间】:2020-08-17 05:14:47
【问题描述】:

我在互联网上发现了这个“React 组件在其状态或道具发生变化时自动重新渲染”,但是如果在道具中我传递了与状态不同的东西,它不会引发渲染,即使道具随着时间发生了变化。

在这段代码中,我在不使用状态的情况下传递了一个道具

父母

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>;
}

感谢你帮我解决了我脑海中的这个混乱

【问题讨论】:

  • 如果你改变了传递给组件的道具,组件将重新渲染。为什么你认为它不会重新渲染?
  • 很难理解你在问什么。考虑改进您的问题。
  • 在您的示例中:与状态相比,您使用了普通变量,这就是您只记录一次的原因。普通变量不会强制重新渲染。

标签: reactjs state render react-props


【解决方案1】:

几天前,我在教我的一个小辈在 react 中的记忆,我想出了一种描述性的方式来展示重新渲染的工作原理。

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


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 功能。

现在我们知道组件在状态改变时重新渲染,但它也可以在它的 props 改变时重新渲染。

让我告诉你我的意思。


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 作为道具传递给子组件。

每次父组件(即计数器)中的计数发生变化时,子组件都会重新渲染。

这是因为两件事。一是 props 发生了变化,二是因为父组件在重新渲染时会强制其子组件重新渲染。

现在您看到当 state 发生变化、props 发生变化和 parent 发生变化时,react 中的重新渲染就会发生。

我们可以通过记忆来阻止孩子进行不必要的重新渲染,我不会在这里讨论。

我希望这会有所帮助。

请原谅我缺少缩进和一般看起来丑陋的 as* 代码。

【讨论】:

  • 很高兴你喜欢它。
  • 非常感谢Siradji,您的解释令人惊叹,并且对主题非常清楚,但这并不是我想要的,我的问题很混乱,所以我编辑了它,我的错,我知道了,希望你现在能明白,非常感谢Siradji!
猜你喜欢
  • 1970-01-01
  • 2017-06-23
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 2017-03-26
相关资源
最近更新 更多