# 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](https://2647972981-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LvLmy8qHKus4tjYXHI4%2F-LvLmyreyxcNGjR6qn1l%2F-LvLnSqwEuUMW8THtwiI%2FgetDerivedStateFromProps.jpg?generation=1575561866020131\&alt=media)

Восстановим код, который был в *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](https://2647972981-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LvLmy8qHKus4tjYXHI4%2F-LvLmyreyxcNGjR6qn1l%2F-LvLnSqzht7eGIFqk8bx%2Fgdsfr-spam.jpg?generation=1575561865844978\&alt=media)

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

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


---

# Agent Instructions: 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:

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

The question should be specific, self-contained, and written in natural language.
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.
