- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试在我的用户成功登录后(在 Login.js 内)使用 React Router 进行简单的重定向,并阻止用户重新访问登录页面(在 index.js 内)。
在 Login.js 中,我有 onSubmit={this.handleSubmit}
在登录按钮标签内,以及 handleSubmit(e)
重定向功能。我在网上尝试了一些其他解决方案,但我认为我对 <Redirect/>
的用法的理解码件错误。
在 index.js 中,我有一个条件来测试用户是否已登录或未登录,并(糟糕地)提醒用户他们无法访问所需页面的原因。我在 Youtube 视频中看到了这一点,但不确定这是否是获得预期效果的最佳方式。
目前,当我成功登录时,警报 You can't login if you are logged in!
已关闭,但我显然不希望在成功登录后立即关闭警报,我希望首先触发重定向。如果我交换括号中的两者,React 会抛出错误。
如何在成功登录后立即触发重定向,但不发送警报 You can't login if you are logged in!
?
Login.js 组件:
import React, { Component } from 'react';
import fire from '../config/Fire.js';
import { Link, Redirect } from 'react-router-dom';
import PasswordMask from 'react-password-mask';
export default class Login extends Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.signup = this.signup.bind(this);
this.state = {
email: '',
password: ''
};
}
handleChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
<Redirect to="/ticket-list"/>;
}
login(e) {
e.preventDefault();
fire.auth().signInWithEmailAndPassword(this.state.email, this.state.password).catch((error) => {
alert(error);
});
}
signup(e){
e.preventDefault();
fire.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).catch((error) => {
alert(error);
})
}
render() {
return (
<div className="m-container">
<h1>Login</h1>
<hr/>
<div className="m-container">
<form onSubmit={this.submitForm}>
<div>
<label for="exampleInputEmail1">Email address: </label>
<br/>
<input
value={this.state.email}
onChange={this.handleChange}
type="text"
name="email"
id="exampleInputEmail1"
placeholder="you@email.com" />
</div>
<div>
<label for="exampleInputPassword1">Password: </label>
<br/>
{/* Margin issue when showing and hiding password */}
<PasswordMask
value={this.state.password}
onChange={this.handleChange}
type="password"
name="password"
id="exampleInputPassword1"
placeholder="**********"
/>
</div>
<br/>
<button
type="submit"
className="button"
onClick={this.login}
onSubmit={this.handleSubmit}>Login</button>
<Link className="button-inv" to="/register">Register</Link>
</form>
</div>
</div>
);
}
}
index.js 组件:
import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import Home from './Home';
import Technician from './Technician';
import About from './About';
import Register from './Register';
import Login from './Login';
import TicketList from './TicketList';
export default class Routes extends Component {
render() {
return (
<Switch>
<Route path="/" exact component={Home} />
<Route path="/technician" exact component={Technician} />
<Route path="/about" exact component={About} />
<Route path="/register" exact render={()=>(
this.props.user ? (alert("You can't register if you are logged in!"), (<Redirect to="/"/>)) : (<Register/>)
)} />
<Route path="/login" exact render={()=>(
this.props.user ? (alert("You can't login if you are logged in!"), (<Redirect to="/ticket-list"/>)) : (<Login/>)
)} />
<Route path="/ticket-list" exact render={()=>(
this.props.user ? (<TicketList/>) : (alert("You must log in to visit this page."), (<Redirect to="/login"/>))
)} />
</Switch>
);
}
};
App.js:
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
import Routes from './routes';
import fire from './config/Fire.js';
// CSS
import './assets/css/App.css';
import './assets/css/Header.css';
import './assets/css/Footer.css';
// Components
import Header from './components/Header';
import Footer from './components/Footer';
class App extends Component {
constructor(props){
super(props);
this.state = {
user:{},
}
}
//When component is done rendering for the first time
componentDidMount(){
this.authListener();
}
// If user logs in (if) or out (else) this is called
authListener() {
fire.auth().onAuthStateChanged((user) => {
//console.log(user);
if (user) {
this.setState({ user });
} else {
this.setState({ user: null });
}
});
}
render() {
return (
<BrowserRouter>
<div className="wrapper">
<Header user={this.state.user} />
<div className="body">
<Routes user={this.state.user} />
</div>
<Footer />
</div>
</BrowserRouter>
);
}
}
export default App;
最佳答案
要解决您的问题,您必须为 Login
/Register
创建单独的组件,并根据用户进行警报和重定向。您将需要 react-router
库中名为 withRouter
的高阶组件。
登录容器:
class LoginContainer extends Component {
constructor(props) {
super(props)
if (props.user) {
alert("You can't login if you are logged in!")
props.history.push('/ticket-list')
}
}
render() {
return <Login />;
}
}
export default withRouter(LoginContainer)
然后像这样在你的Routes
中使用它:
<Route path="/login" render={()=> <LoginContainer user={this.props.user} />} />
与 Register
相同,或者您可以制作一个并获取参数,如 alertMessage
和 redirectTo
并使用它们而不是硬编码值。
另外,我建议你为你的私有(private)路由使用 auth HoC,没有身份验证是无法访问的。
我更喜欢使用新的上下文 API 来共享用户、本地化等实体,所以这里是一个如何使用 React Context
API 制作 PrivateRoute
的示例.
App.js
...
export const UserContext = React.createContext();
...
class App extends Component {
state = {
user: null
}
componentDidMount() {
this.authListener();
}
authListener() {
fire.auth().onAuthStateChanged(user => {
if (user) {
this.setState({ user });
}
});
}
render() {
<UserContext.Provider value={this.state}>
<BrowserRouter>
// another things Switch etc
...
</BrowserRouter>
</UserContext.Provider>
}
}
PrivateRoute.jsx
import React, { Component } from 'react';
import { Route, Redirect } from 'react-router-dom'
import { UserContext } from './App'
const PrivateRoute = ({ component: ComposedComponent, ...rest }) => {
class Authentication extends Component {
handleRender = props => {
if (!this.props.user) {
return <Redirect to="/login" />
} else {
return <ComposedComponent user={this.props.user} {...props} />
}
}
render() {
return (
<Route {...rest} render={this.handleRender} />
);
}
}
return (
<UserContext.Consumer>
{
({ user }) => <Authentication user={user} />
}
</UserContext.Consumer>
)
};
export default PrivateRoute
然后您可以使用 PrivateRoute
而不是 Route
以防您不想在未经身份验证的情况下显示页面。
import PrivateRoute from './PrivateRoute'
...
// all of the component code
render() {
...
<Switch>
<PrivateRoute path="/ticket-list" component={<TicketList />} />
</Switch>
...
}
希望对您有所帮助!祝你好运!
关于javascript - 登录时重定向 - React.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51921419/
我是一名优秀的程序员,十分优秀!