
在 react 中會觸發重新渲染的主要是 props 及 state
是元件外部傳入的參數,只讀屬性, 是不可變的 ( Immutable ),一但建立就不可變,只能透過銷毀,重建改變數據,通過判斷記憶體地址是否一致,來確認對象是不是有經修改過。
this.setState ({ count: this.state.count + 1 }, () => {
console.log(this.state.count);
});
onClick={() => {
this.setState(
(preState, preProps) => {
return { count: preState.count + 1 };
}
);
this.setState(
(preState, preProps) => {
return { count: preState.count + 1 };
}
);
}}

在組件接收到一個新的 prop 或更新後被調用
P.S.但需要特別注意的是,當該元件中任何state被setState設定時,componentDidUpdate都會被重新呼叫。所以必須特別注意目前的邏輯是否有出現無限遞迴的可能。
shouldComponentUpdate(nextProps, nextState) {
return true; // 反回true 更新 false 不更新
}
interface RobotProps {
id: number;
name: string;
email: string;
}
interface RobotState {
random:number
}
const Robot: React.FC<RobotProps,RobotState> = ({ id, name, email }) => {
const value = useContext(appContext)
return (
<div className={styles.cardContainer}>
<img alt="robot" src={`https://robohash.org/${id}`} />
<h2>{name}</h2>
<p>{email}</p>
<p>{value.username}</p>
</div>
);
};
export default Robot;
onClick={this.handlerClick.bind(this)}>
handlerClick = (e) => {
this.setState({ isOpen: !this.state.isOpen });
};