[英]how to redirect to another page when a certain condition is true using javascript
[英]How to Redirect to another page in ReactJS when a IF condition is executed?
如果用戶名和密碼匹配,我想重定向到Dashboard.jsx。 怎么做 ? 我是ReactJS的新手。
在If條件下,我想添加重定向代碼以重定向另一個頁面。 請回應。 在stackoverflow中,最大使用條件是沒有條件,所以這是區別。
var users={
name:'bddebashis',
password:'debashis111249'
}
class Home extends Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
fetch('/api/form-submit-url', {
method: 'POST',
body: data,
});
if(data.get('usr')==users.name && data.get('paswd')==users.password){
<Redirect to='./Dashboard';/>
}
}
// Are You using BrowserRouter means you can use like this
import PropTypes from 'prop-types';
var users={
name:'bddebashis',
password:'debashis111249'
}
class Home extends Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
static contextTypes = {
router: PropTypes.object,
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
fetch('/api/form-submit-url', {
method: 'POST',
body: data,
});
if(data.get('usr')==users.name && data.get('paswd')==users.password){
this.context.router.history.push("/Dashboard")
}
}
}
如果您使用的是React Router,則可以使用重定向組件
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md
<Redirect to="/dashboard" />
在渲染函數中添加重定向組件就足夠了。
通過使用history
模塊,重定向使操作更加容易。 安裝歷史記錄模塊npm install history
然后像這樣配置您的添加路由器。
AppRouter.js
import { Router, Route, Switch } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
export const history = createHistory();
<Router history={history}>
<Route path="/about" component={AboutPage} />
<Route ... />
...
<Router>
然后重定向到另一個組件
import {history} from './AppRouter';
history.push('/dashboard');
import createHistory from 'history/createBrowserHistory';
export const history = createHistory();
<Router history={history}>
<Route />
<Router>
在儀表板上的儀表板組件導入歷史記錄中,使用此行重定向
history.push('/Dashboard');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.