Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created May 15, 2025 09:40
Show Gist options
  • Save sunmeat/cf2cc24687d77f1b75cc8a4544b79c27 to your computer and use it in GitHub Desktop.
Save sunmeat/cf2cc24687d77f1b75cc8a4544b79c27 to your computer and use it in GitHub Desktop.
методы ЖЦ классового компонента
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
console.log('constructor');
}
static getDerivedStateFromProps(props, state) {
console.log('getDerivedStateFromProps');
// пример: синхронизация state с props
return null;
}
componentDidMount() {
console.log('componentDidMount');
// запрос к API, подписка и т.д.
}
shouldComponentUpdate(nextProps, nextState) {
console.log('shouldComponentUpdate');
return true; // вернуть false, если не нужно обновлять
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('getSnapshotBeforeUpdate');
return null; // можно вернуть, например, scroll position
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('componentDidUpdate');
// реагирование на обновления
}
componentWillUnmount() {
console.log('componentWillUnmount');
// очистка ресурсов: таймеров, подписок и т.д.
}
render() {
console.log('render');
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Увеличить
</button>
</div>
);
}
}
export default MyComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment