getDerivedStateFromProps中有两个条件

时间:2019-02-14 09:23:27

标签: reactjs

在我的应用程序的getDerivedStateFromProps下,我必须编写2个这样的条件。

static getDerivedStateFromProps(nextProps) {
      if (nextProps.errors) {
         return { errors: nextProps.errors };
      }

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

         profile.company = !isEmpty(profile.company) ? profile.company : '';
         profile.website = !isEmpty(profile.website) ? profile.website : '';
         profile.location = !isEmpty(profile.location) ? profile.location : '';

         return {
            company: profile.company,
            website: profile.website,
            location: profile.location,
         };
      }

      return null;
   }

但是,这里只有第一个条件有效。我应该如何组织此代码?

1 个答案:

答案 0 :(得分:1)

static getDerivedStateFromProps(nextProps) {
      const result = {};

      if (nextProps.errors) {
         result.errors = nextProps.errors;
      }

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

         profile.company = !isEmpty(profile.company) ? profile.company : '';
         profile.website = !isEmpty(profile.website) ? profile.website : '';
         profile.location = !isEmpty(profile.location) ? profile.location : '';

         result.company = profile.company;
         result.website = profile.website;
         result.location = profile.location;
      }

      return result;
   }