阅读教程后,我设法在代码中找出< Redirect />的用法:
import React from 'react';
import Login from './Login';
import Dashboard from './Dashboard';
import {Route,NavLink,BrowserRouter,Redirect} from 'react-router-dom';
const supportsHistory = 'pushState' in window.history;
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',password: '',redirectToDashboard: false,}
}
//-----------------------LOGIN METHODS-----------------------------
onChangeInput(e) {
this.setState({[e.target.name]:e.target.value});
}
login(e) {
e.preventDefault();
const mainThis = this;
if (mainThis.state.username && mainThis.state.password) {
fetch('APILink')
.then(function(response) {
response.text().then(function(data) {
data = JSON.parse(data);
if (!data.error) {
mainThis.setState({redirectToDashboard:true});
} else {
alert(data.msg);
}
})
})
} else {
alert('Username and Password needed');
}
}
renderRedirect = () => {
if (this.state.redirectToDashboard) {
return <Redirect exact to='/company' />
} else {
return <Redirect exact to='/login' />
}
}
render() {
let renderedComp;
return(
<BrowserRouter
basename='/'
forceRefresh={!supportsHistory}>
<React.Fragment>
{this.renderRedirect()}
<Route exact path="/company" render={()=><Dashboard/>} />
<Route exact path="/login" render={()=><Login login={(e)=>this.login(e)} onChangeInput={(e)=>this.onChangeInput(e)} />} />
</React.Fragment>
</BrowserRouter>
)
}
}
这将基于this.state.redirectToDashboard的值检查要显示的组件,但是由于:
onChangeInput(e) {
this.setState({
[e.target.name]:e.target.value
});
}
每次输入都会重新渲染页面,让我留下:
Warning: You tried to redirect to the same route you’re currently on: “/login”
我知道是什么原因引起了警告,只是我想不出其他方法来完成此工作.我应该进行哪些更改,或者至少要想出一个适当的方法才能完成这项工作?
最佳答案
您可以将Route组件包装在
Switch
中,这样可以一次只渲染其子级中的一个.
然后,您可以将第一个孩子从/重定向添加到/ login,并在redirectToDashboard为true时,将重定向重定向到/ company在Switch之外.
例
<BrowserRouter basename="/" forceRefresh={!supportsHistory}>
<div>
{this.state.redirectToDashboard && <Redirect to="/company" />}
<Switch>
<Redirect exact from="/" to="/login" />
<Route path="/company" component={Dashboard} />
<Route
path="/login"
render={() => (
<Login
login={e => this.login(e)}
onChangeInput={e => this.onChangeInput(e)}
/>
)}
/>
</Switch>
</div>
</BrowserRouter>