Замените componentWillReceiveProps статическим getDerivedStateFromProps - PullRequest
0 голосов
/ 19 января 2019

Я следую руководству и знаю, что componentWillReceiveProps скоро выйдет из React, поэтому я попытался заменить его статическим getDerivedStateFromProps;

Итак, у меня есть форма, где я могу добавить профиль пользователя, а затемотредактируйте этот профиль.С помощью componentWillReceiveProps я получаю данные на странице редактирования профиля и могу их редактировать, но с помощью getDerivedStateFromProps я только получаю их, но ничего не могу набрать в полях ввода.

Может кто-нибудь сказать мне, почему?

Состояние:

state = {
    displaySocialInputs: false,
    handle: '',
    company: '',
    website: '',
    location: '',
    skills: '',
    errors: {},
  };

componentWillReceiveProps:

componentWillReceiveProps(nextProps) {
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors });
    }

    if (nextProps.profile.profile) {
      console.log(nextProps.profile.profile)
      const profile = nextProps.profile.profile;

      // Bring skills array back to CSV
      const skillsCSV = profile.skills.join(',');

      // If profile field doesnt exist, make empty string
      profile.company = !isEmpty(profile.company) ? profile.company : '';
      profile.website = !isEmpty(profile.website) ? profile.website : '';
      profile.location = !isEmpty(profile.location) ? profile.location : '';
      profile.skills= !isEmpty(profile.skills) ? profile.skills : '';

      // Set component fields state
      this.setState({
        handle: profile.handle,
        company: profile.company,
        website: profile.website,
        location: profile.location,
        skills: skillsCSV,
      });
    }
  }

и статический getDerivedStateFromProps, тот, который я поставил вместо вышеуказанного:

static getDerivedStateFromProps(nextProps, prevState) {
    // if there is an error
    if (nextProps.errors !== prevState.errors) {
      // then add it to errors object
      return { errors: nextProps.errors };
    }

    if (nextProps.profile.profile) {
      console.log(nextProps.profile.profile)
      const profile = nextProps.profile.profile;

      // Bring skills array back into CSV
      const skillsCSV = profile.skills.join(',');

      // If profile field doesn't exist, make empty string
      // if is not empty, then use it, else add ''
      profile.company = !isEmpty(profile.company) ? profile.company : '';
      profile.website = !isEmpty(profile.website) ? profile.website : '';
      profile.location = !isEmpty(profile.location) ? profile.location : '';
      profile.skills = !isEmpty(profile.skills) ? profile.skills : '';

      // Set component fields state
      return {
        handle: profile.handle,
        company: profile.company,
        website: profile.website,
        location: profile.location,
        skills: skillsCSV
      }
    }
    return null;
  };

Я много искал в интернете и увидел, что с getDerivedStateFromProps вам нужен компонентDidUpdate:

componentDidUpdate(prevProps, prevState) {
    if (prevProps.errors !== this.props.errors) {
      this.setState({ errors: this.props.errors })
    }

    if (prevProps.profile !== this.props.profile) {
      const profile = this.props.profile.profile;
      // Bring skills array back into CSV
      // join back into a string by comma
      const skillsCSV = profile.skills.join(',');

      // If profile field doesn't exist, make empty string
      // if is not empty, then use it, else add ''
      profile.company = !isEmpty(profile.company) ? profile.company : '';
      profile.website = !isEmpty(profile.website) ? profile.website : '';
      profile.location = !isEmpty(profile.location) ? profile.location : '';
      profile.status = !isEmpty(profile.status) ? profile.status : '';
      profile.skills = !isEmpty(profile.skills) ? profile.skills : '';

      // Set component fields state
      this.setState({
        handle: profile.handle,
        company: profile.company,
        website: profile.website,
        location: profile.location,
        status: profile.status,
        skills: skillsCSV
      });
    }
  }
...