render的执行时机主要分成了两部分:
● 类组件调用setState修改状态
class Foo extends React.Component {
state = { count: 0 };
increment = () => {
const { count } = this.state;
const newCount = count < 10 ? count + 1 : count;
this.setState({ count: newCount });
};
render() {
const { count } = this.state;
console.log("Foo render");
return (
<div>
<h1> {count} </h1>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
点击按钮则调用setState方法,无论count发生变化辩护,控制台都会输出Foo render ,证明render执行了
● 函数组件通过useState hook修改状态
function Foo() {
const [count, setCount] = useState(0);
function increment() {
const newCount = count < 10 ? count + 1 : count;
setCount(newCount);
}
console.log("Foo render");
return (
<div>
<h1> {count} </h1>
<button onClick={increment}>Increment</button>
</div>
);
}
函数组件通过useState这种形式更新数据,当数组的值不发生改变了,就不会触发render
● 类组件重新渲染
class App extends React.Component {
state = { name: "App" };
render() {
return (
<div className="App"> <Foo />
<button onClick={() => this.setState({ name: "App" })}>
Change name
</button>
</div>
);
}
}
function Foo() {
console.log("Foo render");
return (
<div> <h1> Foo </h1></div>
);
}
只要点击了App组件内的Change name按钮,不管Foo其体实现是什么,都会被重新render渲染
● 函数组件重新渲染
function App(){
const [name,setName] = useState('App')
return (
<div className="App"> <Foo />
<button onClick={() => setName("aaa")}> { name }</button>
</div>
)
}
function Foo() {
console.log("Foo render");
return (
<div> <h1> Foo </h1></div>
);
}
可以发现,使用useState来更新状态的时候,只有首次会触发Foo render ,后面并不会导致Foo render