繁体   English   中英

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

[英]Render methods should be a pure function of props and state

我收到错误Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state. 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);

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

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

它应该是:

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

  render() {
    return null;
  }
}

随着有状态功能组件的引入,副作用属于useEffect钩子:

const LoginAuth = () => {
  useEffect(() => {
    navigate(routes.INDEX);
  }, []);

  return null;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM