如果状态更新,React是否会更新依赖于组件状态的所有变量和对象



我想问一下,如果组件状态发生了更改,React是只重新渲染组件,还是更新所有依赖于状态的对象。

如果子组件的任何道具因包含组件的影响而更改,则子组件将参与(级联(渲染。

组件状态的更改将触发所有子组件的重新发布。您可以通过使用PureComponent来改变这种行为(只有在检测到道具更改时才会重新发送(:

const Child = () => {
console.log("child rendering");
return <p>child</p>;
};
class PureChild extends React.PureComponent {
render() {
console.log("pure child rendering");
return <p>PureChild</p>;
}
}
export default function App() {
const [state, setState] = React.useState(0);
return (
<div className="App">
{"state: " + state}
<Child />
<Child />
<Child />
<PureChild />
<PureChild />
<PureChild />
<button onClick={() => setState(!state)}>click</button>
</div>
);
}

https://codesandbox.io/s/reverent-swirles-vt30d?file=/src/App.js

最新更新