--- id: 5a24c314108439a4d403617f title: Manage Updates with Lifecycle Methods challengeType: 6 isRequired: false videoUrl: '' localeTitle: Управление обновлениями с помощью методов жизненного цикла --- ## Description
Другим методом жизненного цикла является componentWillReceiveProps() который вызывается всякий раз, когда компонент получает новые реквизиты. Этот метод получает новый реквизит в качестве аргумента, который обычно записывается как nextProps . Вы можете использовать этот аргумент и сравнить с этим this.props и выполнить действия перед обновлением компонента. Например, вы можете вызвать setState() локально до обработки обновления. Другим методом является componentDidUpdate() и вызывается сразу после повторного рендеринга компонента. Обратите внимание, что рендеринг и установка в жизненном цикле компонентов считаются разными. Когда страница сначала загружается, все компоненты монтируются, и здесь вызывается такие методы, как componentWillMount() и componentDidMount() . После этого, по мере изменения состояния, компоненты переделают себя. Следующая задача охватывает это более подробно.
## Instructions
Детский компонент Dialog получает реквизит message от своего родителя, компонента Controller . Напишите componentWillReceiveProps() в компоненте Dialog и nextProps его в консоли this.props и nextProps . Вам нужно будет передать nextProps в качестве аргумента для этого метода, и хотя можно назвать его чем угодно, назовите его nextProps здесь. Затем добавьте componentDidUpdate() в компонент Dialog и запишите заявление, в котором говорится, что компонент обновлен. Этот метод работает аналогично componentWillUpdate() , который предоставляется вам. Теперь нажмите кнопку, чтобы изменить сообщение и посмотреть консоль браузера. Порядок консольных операторов показывает порядок вызова методов. Примечание. Вам необходимо будет написать методы жизненного цикла в качестве обычных функций, а не как функции стрелок для прохождения тестов (также нет преимуществ при написании методов жизненного цикла в виде функций стрелок).
## Tests
```yml tests: - text: Компонент Controller должен отображать компонент Dialog как дочерний. testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Controller)); return mockedComponent.find("Controller").length === 1 && mockedComponent.find("Dialog").length === 1; })(), "The Controller component should render the Dialog component as a child.");' - text: Метод componentWillReceiveProps в компоненте Dialog должен записывать this.props на консоль. testString: 'assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentWillReceiveProps.toString().replace(/ /g,""); return lifecycleChild.includes("console.log") && lifecycleChild.includes("this.props") })(), "The componentWillReceiveProps method in the Dialog component should log this.props to the console.");' - text: Метод componentWillReceiveProps в компоненте Dialog должен записывать nextProps в консоль. testString: 'assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentWillReceiveProps.toString().replace(/ /g,""); const nextPropsAsParameterTest = /componentWillReceiveProps(| *?= *?)(\(|)nextProps(\)|)( *?=> *?{| *?{|{)/; const nextPropsInConsoleLogTest = /console\.log\(.*?nextProps\b.*?\)/; return ( lifecycleChild.includes("console.log") && nextPropsInConsoleLogTest.test(lifecycleChild) && nextPropsAsParameterTest.test(lifecycleChild) ); })(), "The componentWillReceiveProps method in the Dialog component should log nextProps to the console.");' - text: Компонент Dialog должен вызывать метод componentDidUpdate и записывать сообщение на консоль. testString: 'assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentDidUpdate.toString().replace(/ /g,""); return lifecycleChild.length !== "undefined" && lifecycleChild.includes("console.log"); })(), "The Dialog component should call the componentDidUpdate method and log a message to the console.");' ```
## Challenge Seed
```jsx class Dialog extends React.Component { constructor(props) { super(props); } componentWillUpdate() { console.log('Component is about to update...'); } // change code below this line // change code above this line render() { return

{this.props.message}

} }; class Controller extends React.Component { constructor(props) { super(props); this.state = { message: 'First Message' }; this.changeMessage = this.changeMessage.bind(this); } changeMessage() { this.setState({ message: 'Second Message' }); } render() { return (
); } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```