简体   繁体   English

反应:如何设置页面渲染状态

[英]react: how to set state on page render

I'm working with react and I'm trying to set state on page render but it keeps throwing the below error. 我正在使用react并尝试在页面渲染上设置状态,但它一直抛出以下错误。

---Error---- - -错误 - -

Maximum update depth exceeded. 超过最大更新深度。 This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. 当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React limits the number of nested updates to prevent infinite loops. React限制了嵌套更新的数量,以防止无限循环。

---Error---- - -错误 - -

Below is my code of the sidebar component. 下面是我的侧边栏组件的代码。 I'm using Context API for data management as shown in the code and I'm trying to set state of the role inside the showContext method with the value I'm getting through the Context API Consumer. 我正在使用Context API进行数据管理,如代码中所示,并且尝试使用通过Context API Consumer获得的值来设置showContext方法中角色的状态。

import React, { Component, PropTypes } from "react";
import { Menu, Icon } from "antd";
import { BrowserRouter as Router, Link, Route, Switch } from "react-router-dom";
import AdminPage from "../components/Admin/AdminPage";
import App from "../App";
import "../components/Login/LoginPage";
import { LoginContext } from "../context/LoginContext";

export default class MainMenu extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      roleValue: "admin",
      status: false
    };
    this.showContext = this.showContext.bind(this);
  }

  showContext(context) {

    let role = context;

    if (this.state.roleValue == role) {
      this.setState({
         roleValue : "admin",
      });
    }

  }


  render() {


    if (window.location.href == "http://localhost:8081/") {
      var loginHeader =
        <Menu        
          theme="dark"
          mode="horizontal"
          defaultSelectedKeys={["2"]}
          selectedKeys={[location.pathname]}
        >
          {this.props.children}
          <Menu.Item key="mastering">Mastering</Menu.Item>     
        </Menu>;


    }

    else {
      if (this.state.roleValue == "general") {
        var generalHeader1 =
          <Menu      
            theme="dark"
            mode="horizontal"
            defaultSelectedKeys={["2"]}
            selectedKeys={[location.pathname]}
          >
            {this.props.children}
            <Menu.Item key="mastering">Mastering</Menu.Item>

            <Menu.Item>
              <Link to="/"> Logout</Link>
            </Menu.Item>

            <Menu.Item>
              <Link to="/home">Home</Link>
            </Menu.Item>         
          </Menu>;

      }

      else {
        var generalHeader2 =
          <Menu        
            theme="dark"
            mode="horizontal"
            defaultSelectedKeys={["2"]}
            selectedKeys={[location.pathname]}
          >
            {this.props.children}
            <Menu.Item key="mastering">Mastering</Menu.Item>

            <Menu.Item>
              <Link to="/"> Logout</Link>
            </Menu.Item>

            <Menu.Item>
              <Link to="/admin">Admin</Link>
            </Menu.Item>

            <Menu.Item>
              <Link to="/home">Home</Link>
            </Menu.Item>

          </Menu>;


      }
    }


    return (
      <div>

        {loginHeader}
        {generalHeader1}
        {generalHeader2}

        <LoginContext.Consumer>
          {(context) => (
            this.showContext(context.state.role)
          )
          }
        </LoginContext.Consumer>


      </div>
    );


  }
}

setState() causes a call to render() . setState()导致对render()的调用。 So if you call setState() in render() you will get infinite recursion. 因此,如果在render()调用setState() ,则将获得无限递归。 DON'T DO THIS. 不要这样做。 Instead find the correct way to do what you want within the framework defined by React and the other libraries you use. 而是在React和您使用的其他库定义的框架中找到正确的方法来执行所需的操作。

A React component waits for any change on its own state and props in a normal conditions and when a changes takes place, it calls Render method and expect a component or null to be returned. React组件等待其自身状态的任何更改,并在正常条件下进行支撑,并且当发生更改时,它将调用Render方法并期望返回一个组件或null。

What you did is: Component starts and tries to do its very first render and you set component states which request another render and it set states again and it goes on like this. 您要做的是:组件启动并尝试进行其第一个渲染,然后设置请求另一个渲染的组件状态,然后再次设置状态,这样就继续进行。 It calls each other circularly. 它相互循环调用。

Set state outside of Render method to avoid this situation. 在Render方法之外设置状态以避免这种情况。

You are doing it in wrong way, as you are setting the state inside the render the render loop will be infinite. 您正在以错误的方式进行操作,因为您正在设置渲染内部的状态,因此渲染循环将是无限的。

Please check this link which will help you to resolve your problem, and still if you face any issue after implementation let me know I will love to help you. 请检查此链接,它将帮助您解决问题,如果在实施后仍然遇到任何问题,请告诉我,我将很乐意为您提供帮助。

Reference link : https://reactjs.org/docs/context.html#dynamic-context 参考链接: https : //reactjs.org/docs/context.html#dynamic-context

使用React生命周期方法componentDidMount来处理与setState相关的任务。

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

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