首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用getDerivedStateFromProps

如何使用getDerivedStateFromProps
EN

Stack Overflow用户
提问于 2019-01-31 02:37:02
回答 1查看 146关注 0票数 0

在我的应用程序中,如果用户从登录屏幕登录,我希望导航到仪表板屏幕。我的代码是这样的。

代码语言:javascript
复制
// Login Screen

     componentDidUpdate() {
          const { auth, history } = this.props;
          redirectIfAuthenticated(auth.isAuthenticated, history, './dashboard');
       }

       static getDerivedStateFromProps = (nextProps, prevState) => {
          if (nextProps.errors) 
             return { errors: nextProps.errors }

          return { errors: prevState.errors }
       }


// auth util
export const redirectIfAuthenticated = (isAuthenticated, history, screen) => {
   if (isAuthenticated) { 
      history.push(screen);
   }
}

这与预期的一样。我想知道我做这件事的方式是否正确。我用getDerivedStateFromProps替换了componentWillRecieveProps。现在,我也必须使用componentDidUpdate来实现我使用componentWillRecieveProps时所做的事情。这是正确的吗

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-31 02:51:48

是的,这就是你应该怎么做。看一看getDerivedStateFromProps's documentation

此外,您可以返回null以避免更新状态,因此我会将prevState.errors部件更改为:

代码语言:javascript
复制
 static getDerivedStateFromProps = (nextProps, prevState) => {
          if (nextProps.errors) {
             return { errors: nextProps.errors }
          } else {
           return null
          }
       }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54447364

复制
相关文章

相似问题

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