渲染方法应该是props和state的纯函数

时间:2018-10-21 04:59:27

标签: javascript reactjs

我收到错误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 个答案:

答案 0 :(得分:1)

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

应该在安装组件之后应用副作用,这就是componentDidMount挂钩的目的。

应该是:

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

  render() {
    return null;
  }
}