javascript - 无法在 React Context Api 中保持状态
问题描述
我只是在试验反应上下文 api,我无法在页面重新加载时保持我的状态。每当重新加载页面时,我的状态都会被设置为空。如何在我的上下文中保持状态?我可以使用 localStorage,但我不想在 localStorage 中标记,因为它有一些我不想放在那里的东西(我在这里谈论的是真实应用程序的上下文)。应用程序的流程是这个登录=>将对象传递给=>上下文提供者(通过回调函数)=>用户(通过上下文获取对象)=>在页面重新加载时我失去了状态。
应用组件
...
import React from "react";
import { HashRouter as Router, Route, Switch } from "react-router-dom";
import Login from "./login";
import User from "./user";
import Context from "../context/context";
import AppProvider from "../context/provider";
import "./styles.css";
export default class App extends React.Component {
render() {
return (
<AppProvider>
<div>
<Switch>
<Route path="/" exact component={Login} />
<Route path="/user" exact component={User} />
<Route path="*" component={() => " Not Found"} />
</Switch>
;
</div>
</AppProvider>
);
}
}
App.contextType = Context;
登录组件
...
import React from "react";
import Context from "../context/context";
import {
HashRouter as Router,
Route,
Switch,
Link,
withRouter
} from "react-router-dom";
export default class Login extends React.Component {
constructor() {
super();
this.state = {
object: {
name: "user",
age: "15",
security: "12xy"
}
};
this.submit = this.submit.bind(this);
}
submit() {
const session = this.context.setObject;
session(this.state.object);
this.props.history.push("/user");
}
render() {
console.log(this.context);
return (
<div className="App">
Login
<button onClick={this.submit}>Click me </button>
</div>
);
}
}
Login.contextType = Context;
用户组件
...
import React from "react";
import Context from "../context/context";
export default class User extends React.Component {
constructor() {
super();
this.state = {
user: [
{
name: "Johnny",
job: "Engineer"
}
]
};
this.dosubmit = this.dosubmit.bind(this);
}
componentDidMount() {
var security = this.context.object.security;
if (security !== undefined) {
console.log("security present");
} else {
console.log("not present");
}
}
dosubmit() {
localStorage.clear();
this.props.history.push("/");
}
render() {
return (
<div className="App">
{this.state.user.map(({ name, job }) => {
return (
<div>
<h1> {name}</h1>
<h2> {job} </h2>
<button onClick={this.dosubmit}>Click for logout </button>
</div>
);
})}
</div>
);
}
}
User.contextType = Context;
上下文提供者组件
...
import React, { Component, createContext } from "react";
import Context from "./context";
class AppProvider extends Component {
state = {
object: {}
};
setObject(object) {
this.setState({ object: object });
}
componentDidUpdate(prevProps, prevState) {
if (this.state.object !== prevState.object) {
localStorage.setItem("token", JSON.stringify(this.state.object));
if (this.state.object !== undefined) {
this.setState({ object: this.state.object });
}
}
}
render() {
console.log("Provider", this.state);
return (
<Context.Provider
value={{
object: this.state.object,
setObject: this.setObject.bind(this)
}}
>
{this.props.children}
</Context.Provider>
);
}
}
export default AppProvider;
...
我的示例是https://codesandbox.io/s/trusting-hertz-tql5e?file=/src/App.js
解决方案
推荐阅读
- python - /search/ 'QuerySet' 对象的 AttributeError 没有属性 'facet'
- android - 读取包含链接的 XML 文件 (Android)
- c# - 数组中是否可以有不同颜色的矩形?
- nativescript - HThangEventCreate 失败?
- hyperledger-fabric - 是否可以根据 Hyperledger Fabric 中的实时流量来扩大节点数量?
- android - 我可以只将时间转换为时间戳吗?
- sql - 返回一个包含多列的表
- java - 如何制作一个在我按下时播放歌曲的按钮,一旦我再次按下它就会停止歌曲?
- python - PYTORCH支持的“torch.nn.CTCLoss”和torch_baidu_ctc支持的“CTCLoss”有区别吗?
- python - python中的process.pid在macOS mojave上给出错误的值