> For the complete documentation index, see [llms.txt](https://max-frontend.gitbook.io/react-course-ru-v2/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://max-frontend.gitbook.io/react-course-ru-v2/spam-filtr/getderivedstatefromprops.md).

# getDerivedStateFromProps

Сигнатура метода: `static getDerivedStateFromProps(props, state)` и [документация](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops), в которой описано, что данный метод нужен для очень редких случаев. Мы сами выдумали себе задачу и ограничения для решения, поэтому он нам пригодится.

Этот метод жизненного цикла в целом похож на *CWRP*, но есть отличия:

* так как метод static - нет доступа к this
* из метода должно возвращаться новое состояние или `null`, если "обновлений" не планируется.
* для первого рендера (*initial render*) - тоже вызывается

Один из лучших способов понять, что происходит - `console.log`

*src/components/News.js*

```jsx
...
static getDerivedStateFromProps(props, state) {
  console.log(props)
  console.log(state)
  return {
    filteredNews: props.data,
  }
}

// удалите componentWillReceiveProps
...
```

Попробуйте добавить новость.

![getDerivedStateFromProps](/files/-LvLnSqwEuUMW8THtwiI)

Восстановим код, который был в *CWRP*, но уже для *getDerivedStateFromProps* (*gDSFR*)

*src/components/News.js*

```jsx
static getDerivedStateFromProps(props, state) {
  let nextFilteredNews = [...props.data] // было nextProps - переименовали

  nextFilteredNews.forEach((item, index) => {
    if (item.bigText.toLowerCase().indexOf('pubg') !== -1) {
      item.bigText = 'СПАМ'
    }
  })

  return { // возвращаем новое состояние
    filteredNews: nextFilteredNews,
  }
}
```

![gdsfr-spam](/files/-LvLnSqzht7eGIFqk8bx)

**Итого**: научились использовать современный getDerivedStateFromProps

[Исходный код](https://github.com/maxfarseer/react-course-ru-v2/tree/chp17-getDerivedStateFromProps)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://max-frontend.gitbook.io/react-course-ru-v2/spam-filtr/getderivedstatefromprops.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
