freeCodeCamp/curriculum/challenges/russian/03-front-end-libraries/react/manage-updates-with-lifecyc...

7.1 KiB
Raw Blame History

id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d403617f Manage Updates with Lifecycle Methods 6 false Управление обновлениями с помощью методов жизненного цикла

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

tests:
  - text: Компонент <code>Controller</code> должен отображать компонент <code>Dialog</code> как дочерний.
    testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Controller)); return mockedComponent.find("Controller").length === 1 && mockedComponent.find("Dialog").length === 1; })(), "The <code>Controller</code> component should render the <code>Dialog</code> component as a child.");'
  - text: Метод <code>componentWillReceiveProps</code> в компоненте <code>Dialog</code> должен записывать <code>this.props</code> на консоль.
    testString: 'assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentWillReceiveProps.toString().replace(/ /g,""); return lifecycleChild.includes("console.log") && lifecycleChild.includes("this.props") })(), "The <code>componentWillReceiveProps</code> method in the <code>Dialog</code> component should log <code>this.props</code> to the console.");'
  - text: Метод <code>componentWillReceiveProps</code> в компоненте <code>Dialog</code> должен записывать <code>nextProps</code> в консоль.
    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 <code>componentWillReceiveProps</code> method in the <code>Dialog</code> component should log <code>nextProps</code> to the console.");'
  - text: Компонент <code>Dialog</code> должен вызывать метод <code>componentDidUpdate</code> и записывать сообщение на консоль.
    testString: 'assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentDidUpdate.toString().replace(/ /g,""); return lifecycleChild.length !== "undefined" && lifecycleChild.includes("console.log"); })(), "The <code>Dialog</code> component should call the <code>componentDidUpdate</code> method and log a message to the console.");'

Challenge Seed

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 <h1>{this.props.message}</h1>
  }
};

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 (
      <div>
        <button onClick={this.changeMessage}>Update</button>
        <Dialog message={this.state.message}/>
      </div>
    );
  }
};

After Test

console.info('after the test');

Solution

// solution required