我在互联网上发现这个“React components automatically re-render whenever there are a change in their state or props”,但是如果我在 prop 中传递不同于状态的东西,它不会引发渲染,即使 Prop 在时间上发生了变化。
在这段代码中,我在不使用状态的情况下传递了一个 prop
parent
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} />;
}
child
import React from "react";
export default function Child(props) {
console.log("render from child"); //console.log once
return <h1>{props.count}</h1>;
}
谢谢你帮我解决了这个乱七八糟的问题
几天前,我在用 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>
</>
}
这里我有另一个组件,它是计数器组件的子组件。我将计数作为 Prop 传递给子组件。
每当父组件(即计数器)中的计数发生变化时,子组件将重新渲染。
这是因为两件事。一是 props 变了,二是因为父组件在重新渲染时会强制其子组件重新渲染。
现在你看到当状态改变, Prop 改变和父级改变时,react 中的重新渲染发生了。
我们可以使用内存来阻止 child 进行不必要的重新渲染,我不会在这里谈论它。
希望对您有所帮助。
请原谅我缺乏缩进和丑陋的代码。