作为Treehouse课程的一部分,我正在构建一个使用基本身份验证访问API的React APP。在我的提供程序中,我维护用户的状态以及登录和注销功能。
所有其他组件都可以访问它,并且在应用程序中单击的每条路线都不会刷新状态。但是,当引发错误时,应用程序会将用户重定向到适当的页面,但整个用户状态会在登录前重置为初始状态。
例如。试图访问他们未创建的课程的course /:id / update路线的用户已正确推送(this.props.history.push())到/ forbidden路线。它也将其签出。
我尝试过使用本地存储。我什至尝试使用js-cookie包来维护状态。我尝试将Consumer添加到每个组件中,但也没有用。
我不认为需要使错误组件不仅仅是功能组件,因此我没有尝试使它们成为类甚至是纯组件。
我的背景
import { withRouter } from 'react-router-dom';
import axios from 'axios';
import Cookies from 'js-cookie';
export const UserContext = React.createContext();
export const Consumer = UserContext.Consumer;
class Provider extends Component {
state = {
authenticatedUser: Cookies.getJSON('authenticatedUser') || null,
user: {},
emailAddress: '',
password: '',
isLoggedIn: false
}
handleSignIn = (e, emailAddress, password) => {
if (e) {
e.preventDefault();
}
// Axios fetch request
axios.get('http://localhost:5000/api/users', {
auth:{
username: emailAddress,
password: password
}
})
.then(res => {
if(res.status === 200){
let user = res.data;
this.setState({
user: user,
emailAddress: user.emailAddress,
password: user.password,
isLoggedIn: true
});
Cookies.set('authenticatedUser', JSON.stringify(this.state.user))
window.localStorage.setItem("emailAddress", emailAddress);
window.localStorage.setItem("password", password);
this.props.history.push('/courses');
}
}).catch(err => {
if(err.response.status === 400){
this.props.history.push('/notfound');
console.log("Error Parsing and Fetching Data", err)
} else if (err.response.status === 500) {
this.props.history.push('/error');
console.log("Error Parsing and Fetching Data", err)
}
})
}
handleSignOut = () => {
window.localStorage.clear();
this.setState({
user: {},
emailAddress: '',
password: '',
isLoggedIn: false
});
Cookies.remove('authenticatedUser');
this.props.history.push('/courses');
}
render() {
const { authenticatedUser } = this.state;
return (
<UserContext.Provider value={
{
authenticatedUser,
user: this.state.user,
emailAddress: this.state.emailAddress,
password: this.state.password,
isLoggedIn: this.state.isLoggedIn,
signIn: this.handleSignIn,
signOut: this.handleSignOut
}
}>
{this.props.children}
</UserContext.Provider>
);
}
}
export default withRouter(Provider);
我的一个错误组件(用于localhost:3000 / error):
import '../styles/404.css';
const Error = () => (
<div id="notfound">
<div className="notfound">
<div className="notfound-404">
<h1><span>E</span><span>R</span><span>R</span><span>O</span><span>R</span></h1>
</div>
<h2>Sorry! We just encountered an unexpected error!</h2>
</div>
</div>
//<!-- This templates was made by Colorlib (https://colorlib.com) -->//
);
export default Error;```