代码之家  ›  专栏  ›  技术社区  ›  Darren

呈现方法应该是props和state的纯函数

  •  2
  • Darren  · 技术社区  · 6 年前

    我收到的错误是 Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state. .

    似乎是因为这个代码

    const LoginAuth = () => {
      navigate(routes.INDEX);
      return null;
    };
    

    去除 navigate(routes.INDEX); 停止错误。

    代码有什么问题?我是否应该使用其他方法重定向 authUser ? 感谢您的帮助。

    它是一部分

    import React from 'react';
    import { navigate } from 'gatsby';
    
    import AuthUserContext from './AuthUserContext';
    import withAuthentication from './withAuthentication';
    
    import Layout from './Layout';
    import LoginForm from './LoginForm';    
    import * as routes from '../../constants/routes';
    
    const LoginAuth = () => {
      navigate(routes.INDEX);
      return null;
    };
    
    const LoginPage = () => (
      <Layout>
        <Transition>
          <AuthUserContext.Consumer>
            {authUser => (authUser ? <LoginAuth /> : <LoginNonAuth />)}
          </AuthUserContext.Consumer>
        </Transition>
      </Layout>
    );
    
    const LoginNonAuth = () => <LoginForm />;
    
    export default withAuthentication(LoginPage);
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Estus Flask    6 年前

    功能组件应该是纯功能,即不包含副作用,而 navigate() 提供副作用。

    副作用应该在组件安装后应用,这就是 componentDidMount 钩子。

    应该是:

    class LoginAuth extends Component {
      componentDidMount() {
        navigate(routes.INDEX);
      }
    
      render() {
        return null;
      }
    }