Перейти к содержанию
Skillpedia
Сайты и интерфейсы (фронтенд)40k · #7387

react18-lifecycle-patterns

Что он делает

Помогает обновить старые методы жизненного цикла ('lifecycle') в коде React до новых версий. Показывает, как перенести части кода в правильные места, чтобы они хорошо работали с актуальными версиями React.

Когда использовать

  • ✓Когда в вашем коде React используются методы жизненного цикла, которые больше не рекомендуются.
  • ✓Когда нужно решить, использовать 'getDerivedStateFromProps' или 'componentDidUpdate'.
  • ✓Когда нужно добавить 'getSnapshotBeforeUpdate' для обработки обновлений.

Ссылка на скилл

https://github.com/github/awesome-copilot/blob/main/skills/react18-lifecycle-patterns/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/github/awesome-copilot/blob/main/skills/react18-lifecycle-patterns/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Как перенести метод 'componentWillMount', который задает начальное состояние в моем компоненте React?”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Это руководство сравнивает, что делает старый метод, с новыми способами выполнить то же самое в React 18. Оно направляет вас к конкретным примерам в зависимости от функции старого метода.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

React 18 Lifecycle Patterns

Reference for migrating the three unsafe class component lifecycle methods to React 18.3.1 compliant patterns.

Quick Decision Guide

Before migrating any lifecycle method, identify the semantic category of what the method does. Wrong category = wrong migration. The table below routes you to the correct reference file.

componentWillMount - what does it do?

What it does Correct migration Reference
Sets initial state (this.setState(...)) Move to constructor → componentWillMount.md
Runs a side effect (fetch, subscription, DOM) Move to componentDidMount → componentWillMount.md
Derives initial state from props Move to constructor with props → componentWillMount.md

componentWillReceiveProps - what does it do?

What it does Correct migration Reference
Async side effect triggered by prop change (fetch, cancel) componentDidUpdate → componentWillReceiveProps.md
Pure state derivation from new props (no side effects) getDerivedStateFromProps → componentWillReceiveProps.md

componentWillUpdate - what does it do?

What it does Correct migration Reference
Reads the DOM before update (scroll, size, position) getSnapshotBeforeUpdate → componentWillUpdate.md
Cancels requests / runs effects before update componentDidUpdate with prev comparison → componentWillUpdate.md

The UNSAFE_ Prefix Rule

Never use UNSAFE_componentWillMount, UNSAFE_componentWillReceiveProps, or UNSAFE_componentWillUpdate as a permanent fix.

Prefixing suppresses the React 18.3.1 warning but does NOT:

  • Fix concurrent mode safety issues
  • Prepare the codebase for React 19 (where these are removed, with or without the prefix)
  • Fix the underlying semantic problem the migration is meant to address

The UNSAFE_ prefix is only appropriate as a temporary hold while scheduling the real migration sprint. Mark any UNSAFE_ prefix additions with:

// TODO: React 19 will remove this. Migrate before React 19 upgrade.
// UNSAFE_ prefix added temporarily - replace with componentDidMount / getDerivedStateFromProps / etc.

Reference Files

Read the full reference file for the lifecycle method you are migrating:

  • references/componentWillMount.md - 3 cases with full before/after code
  • references/componentWillReceiveProps.md - getDerivedStateFromProps trap warnings, full examples
  • references/componentWillUpdate.md - getSnapshotBeforeUpdate + componentDidUpdate pairing

Read the relevant file before writing any migration code.

Частые вопросы

Что такое 'методы жизненного цикла'?

Это специальные функции компонентов React, которые выполняют код в определенные моменты: при создании, обновлении или удалении компонента.

Почему нельзя просто использовать старые методы, например 'UNSAFE_componentWillMount'?

Префикс 'UNSAFE_' лишь скрывает предупреждение, но не решает проблем совместимости с новыми версиями React. Это временное решение, а не постоянное.

Где найти примеры кода для миграции?

Подробные примеры находятся в отдельных справочных файлах, например 'componentWillMount.md', 'componentWillReceiveProps.md' и 'componentWillUpdate.md', на которые ссылается руководство.

Подробности

Оригинальное описание автора

Provides exact before/after migration patterns for the three unsafe class component lifecycle methods - componentWillMount, componentWillReceiveProps, and componentWillUpdate - targeting React 18.3.1. Use this skill whenever a class component needs its lifecycle methods migrated, when deciding between getDerivedStateFromProps vs componentDidUpdate, when adding getSnapshotBeforeUpdate, or when fixi

repo: github/awesome-copilot

Популярность

Звёзды на GitHub
40k
Место в рейтинге
#7387
Лицензия
MIT
Обновлён
15.10.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы