抱歉,这听起来很愚蠢。我正在尝试将用户登录后重定向到应用程序的内容页面。我当前的实现正确更改了地址栏中的URL,但未呈现组件并显示空白页面。我在这里缺少什么吗?你能建议我想念什么吗?
我尝试使用Google搜索,但无法正常工作。这是我尝试过的一些链接。
1- https://tylermcginnis.com/react-router-programmatically-navigate/
2- https://learnwithparam.com/blog/redirect-route-in-react-router/
3- Programmatically navigate using react router
登录组件
def print_variables(vars):
for i in range(len(vars)):
print(f"{i + 1}: {vars[i]}")
print_variables(["Red", "Green", "Blue", "Orange", "Yellow"])
应用程序组件:
class Login extends React.Component {
handleSubmit(e) {
e.preventDefault();
var value = true;
localStorage.setItem('userLoggedIn', JSON.stringify(value));
this.setState({
toUsers: true
})
//this.props.history.push('/users')
}
render() {
if (this.state.toUsers === true) {
return <Redirect to="/users" />
}
return (
<div className="Login">
<form onSubmit={this.handleSubmit}>
Email
<input
type="text"
value={this.state.email}
onChange={this.handleEmailChange}
/>
Password
<input
type="text"
value={this.state.password}
onChange={this.handlePasswordChange}
/>
<button>
Login
</button>
</form>
</div>
);
}
}
export default Login;
决定应显示登录页面还是应用程序内容页面的组件
import React, { Component } from 'react';
import { BrowserRouter, HashRouter, Switch, Route } from 'react-router-dom';
import Navigation from './common/Navigation';
import Users from './users/Users.jsx';
import Roles from './roles/Roles.jsx';
import ProtectedRoute from './authentication/ProtectedRoute.jsx';
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
return <Navigation>
<Switch>
<Route exact path="/users" component={Users} />
<Route exact path="/roles" component={Roles} />
<Route render={() => <div>Not Found</div>} />
</Switch>
</Navigation>
}
}
呈现应用的主要应用组件
export default class AppAuthenticated extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
toUsers: false,
isUserLoggedIn: false
};
}
componentDidMount() {
const isUserLoggedIn = JSON.parse(localStorage.getItem('userLoggedIn'));
this.setState({
isUserLoggedIn: isUserLoggedIn
});
}
render() {
return (
<>
{this.state.isUserLoggedIn ? (
<App />
) : (
<Login />
)}
</>
);
}
}
预期的行为:成功登录用户后,应将其重定向到“应用”组件,在该组件中,我定义了用户登录后可以访问的所有路由
答案 0 :(得分:-1)
在app.js中,将一个prop传递给登录组件,该组件可以更改容器状态以呈现内容页面。
setLoggedIn = ()=>{
this.setState({isUserLoggedIn: true});
}
render() {
return (
<>
{this.state.isUserLoggedIn ? (
<App />
) : (
<Login loginSuccess={this.setLoggedIn} />
)}
</>
);
}
然后在您的登录组件中...
handleSubmit(e) {
e.preventDefault();
var value = true;
localStorage.setItem('userLoggedIn', JSON.stringify(value));
this.setState({
toUsers: true
})
this.props.loginSuccess();
//this.props.history.push('/users')
}
答案 1 :(得分:-1)
setLoggedIn = ()=>{
this.setState({isUserLoggedIn: true});
}
render() {
return (
<>
{this.state.isUserLoggedIn ? (
<App />
) : (
<Login loginSuccess={this.setLoggedIn} />
)}
</>
);
}
在您过去的道具@maddy中缺少此内容