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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52912238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:03:02  来源:igfitidea点击:

Render methods should be a pure function of props and state

javascriptreactjs

提问by Darren

I am receiving the error of 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.

It appears that it is because of this code

看来是因为这段代码

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

removing navigate(routes.INDEX);stops the error.

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

What is wrong with the code? Should I be using another method to redirect an authUser?Any help is appreciated.

代码有什么问题?我应该使用另一种方法来重定向authUser吗?任何帮助表示赞赏。

It is a part of

它是的一部分

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);

回答by Estus Flask

Functional components are expected to be pure functions, i.e. contain no side effects, while navigate()provides side effects.

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

Side effects are supposed to be applied after the component is mounted, that's the purpose of componentDidMounthook.

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

It should be:

它应该是:

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

  render() {
    return null;
  }
}