reactjs - 警告:通过回调页面访问应用程序并从此处更新上下文时更新状态转换
问题描述
我有一个由两个页面组成的应用程序,一个主页和一个回调页面。在层服务(例如社交网络或其他)上进行身份验证后,用户将被重定向到我的应用程序的回调页面。该应用程序使用 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_data
Context 组件的状态,但不会触发警告(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;
解决方案
推荐阅读
- ios - 反应原生视频:iOS 上的全屏在退出时会中断布局
- java - 是否可以在 Xamarin 中检索存储在 Java 中的 Android 共享首选项
- django - 如何禁用 Django-OTP / 双重认证 / 2FA
- python - Python 3.x:如何使用 ast 搜索打印语句
- android - 如何在 Android Q 上从应用程序执行 shell 脚本
- prometheus - 有没有办法为具有相似名称的多个 ENUM 指标设置警报
- flutter - Flutter:无法加载 PNG 资源
- python - 有没有办法将 Powershell、Python 脚本转换为 Bash 脚本?
- vue.js - 如何在 vuejs 2.5.x 中正确使用插槽范围?
- ios - 为什么在iOS模拟器中实际启动屏幕出现之前会出现白屏