如果用户名和密码匹配,我想重定向到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';/>
}
}
答案 0 :(得分:5)
// 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")
}
}
}
答案 1 :(得分:0)
如果您使用的是React Router,则可以使用Redirect组件
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md
<Redirect to="/dashboard" />
在渲染函数中添加Redirect组件就足够了。
答案 2 :(得分:0)
使用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>
然后重定向到另一个component.like
import {history} from './AppRouter';
history.push('/dashboard');
答案 3 :(得分:0)
import createHistory from 'history/createBrowserHistory';
export const history = createHistory();
<Router history={history}>
<Route />
<Router>
在您的仪表板组件中 在仪表板中导入历史记录 使用此行重定向
history.push('/Dashboard');