超过最大深度,但setState仅应调用一次

时间:2019-03-22 16:59:57

标签: javascript reactjs

我的代码在这里有问题。当数据未定义或等于false时,只会出现错误Maximum depth exceeded。但是,这是怎么发生的呢? setState方法仅应调用一次,并且如果该方法将状态设置为false,id是否应该再设置任何状态?我的错误在哪里。

class App extends Component {
  constructor(props) {
    super(props);
    this.changeLogin = this.changeLogin.bind(this);
    //Loggedin is false
    this.state = {
      loggedIn: undefined
    };
  }

  componentDidMount() {
    communicate("getToken").then(data => {
      //if no data is available
      if (!data) {
        if (this.state.loggedIn === undefined)
          this.setState({
            loggedIn: false
          });
      }
      //Fetch the key
      else {
        let reqBody =
          "refresh_token=" + data.refresh_token + "&grant_type=refresh_token";
        //Fetch via refresh_token
        fetch(conf.apiDomain + "/oauth/token", {
          method: "POST",
          body: reqBody,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF8",
            Authorization: "Basic Y2xpZW50OlRlc3Q="
          }
        })
          .then(response => response.json())
          .then(json => {
            //if error exists
            if (json.error) {
              throw new Error("Token not valid");
            } else {
              //save the new tokens in the json file
              communicate("saveToken", json).then(res => {
                //Set the loginstate
                this.setState({
                  loggedIn: true
                });
              });
            }
          })
          .catch(err => {
            if (this.state.loggedIn === undefined) {
              this.setState({
                loggedIn: false
              });
            }
          });
      }
    });
  }

  //only for the logincomponent
  changeLogin() {
    this.setState({
      loggedIn: !this.state.loggedIn
    });
  }

  render() {
    return (
      <Router>
        <MuiThemeProvider theme={theme}>
          <Decider loggedIn={this.state.loggedIn} />
          <Route
            path="/login/"
            render={() => {
              return <Login changeLogin={this.changeLogin} />;
            }}
          />
          <AppRoute
            path="/app/"
            component={Pyl}
            loggedIn={this.state.loggedIn}
          />
        </MuiThemeProvider>
      </Router>
    );
  }
}

如果没有数据,则错误发生在if(!data)上;如果数据存在但无效,则错误出现在.catch语句中

完全错误MSG:Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

StackTrace:https://ibb.co/jZKKJT1

Github的完整代码:https://github.com/precodeeu/pyl

jsfiddle(works):https://jsfiddle.net/L8anmhvx/3/

1 个答案:

答案 0 :(得分:1)

似乎真正的错误来自Decider和您的路由。 在Decider中,当loginIn = false时,您似乎正在向后重定向,从而创建了无限循环。