首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >componentWillRecieveProps到getDerivedStateFromProps转换

componentWillRecieveProps到getDerivedStateFromProps转换
EN

Stack Overflow用户
提问于 2019-02-14 05:14:27
回答 2查看 102关注 0票数 1

我正在重构我的反应性应用程序。我想用componentWillRecieveProps代替getDerivedStateFromProps。由于getDerivedStateFromProps不支持setState,所以我只能使用下面的代码。如何将其转换为getDerivedStateFromProps?

代码语言:javascript
复制
   componentWillReceiveProps(nextProps) {
      if (nextProps.errors) {
         this.setState({ 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 : ''; 

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

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-14 07:30:57

更新后的状态应该从getDerivedStateFromProps钩子返回。如果不应该更新状态,则返回null

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2019-02-14 05:26:30

您可能不需要派生状态,为此可以使用componentDidUpdate()方法。与getDerivedStateFromProps不同,这不是静态的,因此您应该能够使用this.setState()。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54683607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档