首页 > 解决方案 > 警告:通过回调页面访问应用程序并从此处更新上下文时更新状态转换

问题描述

我有一个由两个页面组成的应用程序,一个主页和一个回调页面。在层服务(例如社交网络或其他)上进行身份验证后,用户将被重定向到我的应用程序的回调页面。该应用程序使用 react-context api,我想存储在回调页面的查询字符串中找到的所有数据。很快我想打开我的应用程序的一个页面,而不是主页,并从此页面更新应用程序的上下文。

这就是本教程中为 Auth0 实现的目标。该应用程序由 5 个非常短的文件组成,我将在这里复制它们。

问题是我http://127.0.0.1:3000/callback在浏览器中访问时收到警告。警告是Warning: Cannot update during an existing state transition (such as within渲染). Render methods should be a pure function of props and state.Auth0 教程中,这个警告没有出现,但是状态更新是在一个专用函数中进行的,我不知道如何用我自己的组件来重现这个工作。

要重现警告,请使用create-react-app并使用帖子末尾的文件。这个玩具示例的目标是设置unused_dataContext 组件的状态,但不会触发警告(unused_data实际设置)。

编辑:嗯,我学习了 redux,当我使用 redux 时一切正常,所以我仍然不知道为什么会出错,但现在一切都简单多了:)


应用程序.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Context from "./Context";
import Callback from './Callback'
import Home from './Home'

class App extends Component {
  render() {
    return (
      <div className="App">
        <Context>
          <Router>
            <Switch>
              <Route exact path="/" component={Home} />
              <Route path="/callback" component={Callback} />
            </Switch>
          </Router>
        </Context>
      </div>
    );
  }
}

export default App;

上下文.js

import React, {Component} from "react";
import {Provider} from "./contextDefs";


class Context extends Component {
  state = {
    unused_data: ""
  };

  changeState = () => {
    this.setValue()
  }

  setValue = () => {
    this.setState({
      unused_data: "has been set up",
    })
  }

  render() {
    const providerValue = {
      ...this.state,
      changeState: this.changeState,
    };
    return (
      <Provider value={providerValue}>
        {this.props.children}
      </Provider>
    );
  }
}

export default Context;

回调.js

import React from "react";
import {Redirect} from "react-router-dom";

import {Consumer} from "./contextDefs";

const callback = props => (
  <Consumer>
    {({changeState}) => {
        changeState();
        return <Redirect to="/"/>;
      }
    }
  </Consumer>
)

export default callback;

contextDefs.js

import { createContext } from "react";

const Context = createContext({
    unused_data: "",
    changeState: () => {},
  });

export const Provider = Context.Provider;
export const Consumer = Context.Consumer;

主页.js

import React from "react";

const AuthTwitter = props =>  {
  return (
  <div>
    Test
  </div>
  );
}

export default AuthTwitter;

标签: reactjsreact-context

解决方案


推荐阅读