我只是尝试使用react context 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