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。
答案 0 :(得分:0)
问题在于,您的PrivateRoute中有一个名为userLogged
的常量变量,该变量以值false
初始化。如果变量为true
,则呈现定义的组件。如果它是false
,则重定向ot /login
。
userLogged
的值始终为false
,因此您始终重定向到/login
。建议您在父组件App
中或通过使用redux
中的商店来处理登录状态。
答案 1 :(得分:0)
使用“历史记录” 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)登录后,使用“用户”键将一些数据存储在本地存储中。
b)基于此“用户”对象的localStorage路由将在prBivateRoute.js中发生
c)如果要注销清除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;