
[英]Can't redirect using props.history.push with react-router
[英]props.history.push() doesn't redirect
props.history.push(“/”)不重定向。
我确实搜索了这个问题的解决方案,找不到问题出在哪里,这让我发疯。
index.js
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createBrowserHistory } from 'history';
import configureStore from './store/configureStore';
import App from './App';
//import registerServiceWorker from './registerServiceWorker';
// Create browser history to use in the Redux store
const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const history = createBrowserHistory({ basename: baseUrl });
// Get the application-wide store instance, prepopulating with state from the server where available.
const initialState = window.initialReduxState;
const store = configureStore(history, initialState);
//Render app on "root" <div> in index.html
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById('root'));
//registerServiceWorker();
app.js
import React from 'react';
import { Route, Switch } from 'react-router';
import Home from './components/Home';
import Login from './components/Login/Login';
import Counter from './components/Counter';
import FetchData from './components/FetchData';
import { PrivateRoute } from './components/PrivateRoutes/PrivateRoute';
const App = (props) => {
return (
<Switch>
<Route path="/login" component={Login}/>
<PrivateRoute path="/" component={Home} />
<Route path='/counter' component={Counter} />
<Route path='/fetchdata/:startDateIndex?' component={FetchData} />
</Switch>
);
}
export default App;
Login.js
import React, { useState } from 'react';
import { withRouter, Redirect, history } from 'react-router-dom'
import { Form, Label, FormGroup, FormControl, Button } from 'react-bootstrap';
import Home from '../Home';
//Login user
function LoginUser(username, password, callback) {
console.log("Atemt to login..." + " " + username);
fetch('api/SampleData/Login', {
method: "POST",
body: JSON.stringify({
email: username,
password: password,
})
}).then(response => response.json())
.then(json =>callback(json))
}
function Login(props) {
var logged = false;
var data = { username: '', password: '', };
function getUsername(event) {
data.username = event.target.value;
console.log(data);
}
function getPassword(event) {
data.password = event.target.value;
console.log(data);
}
function requestCallback(res) {
if (res[0] === "connected") {
props.history.push('/');
console.log(props.history);
}
}
if (logged === true) {
return (<Redirect to="/" component={Home} />);
}
return (
<div style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)' }}>
<Form >
<FormGroup controlId="formBasicEmail">
<Label>Email address</Label>
<FormControl type="email" placeholder="Enter email" onChange={getUsername} />
</FormGroup>
<FormGroup controlId="formBasicPassword">
<Label>Password</Label>
<FormControl type="password" placeholder="Password" onChange={getPassword} />
</FormGroup>
<Button variant="primary" onClick={() => LoginUser(data.username, data.password, requestCallback)} style={{ margin: '0 auto', display: 'block', width: '100px' }}>
Login
</Button>
</Form>
</div>
);
}
export default withRouter(Login);
正如您所看到的,Login组件包含withRouter(Login)。 Login.js文件中的console.log(props)显示历史记录传递给props。
问题是在你的PrivateRoute中有一个名为userLogged
的常量变量,它以值false
启动。 如果变量为true
,则呈现定义的组件。 如果为false
,则重定向ot /login
。
userLogged
的值始终为false
,因此您始终重定向到/login
。 我建议您在父组件App
或通过使用redux
中的商店来处理您的登录状态。
使用'history'npm包
1)App.js
import React, { Component } from "react";
import { Route, Router } from "react-router-dom";
import { createBrowserHistory } from "history";
import Dashboard from "./components/dashboard.js ";
import Login from "./components/login.js";
import Profile from "./components/profile.js";
import PrivateRoute from "./privateRoute.js";
export const history = createBrowserHistory();
//refer 'history' for wanted component like profile.js
class App extends Component {
render() {
return (
<Router history={history}>
<div>
<PrivateRoute
path="/"
component={Dashboard}
exact
/>
<Route path="/login" component={Login} exact />
<PrivateRoute path="/profile" component={Profile} />
</div>
</Router>
);
}
}
export default App;
a)登录后,使用密钥“user”将一些数据存储在本地存储中。
b)基于localStorage路由中的这个“用户”对象将在prBivateRoute.js中进行
c)如果要注销clear localStorage,它将导航到loginPage
2)privateRoute.js
import React from "react";
import { Route, Redirect } from "react-router-dom";
const PrivateRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
if (localStorage.getItem("user")!= "") {
return <Component />;
}else {
return <Redirect to={{ pathname: "/login" }} />;
}
}}
/>
);
};
3)profile.js
import React, { Component } from "react";
import { history } from "./App.js";
class Profile extends Component {
goBack = () => {
history.push("/");
};
render() {
<button onClick={() => this.goBack()}> back to dashboard </button>;
}
}
export default Profile;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.