props.history.push() 不重定向

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) 显示历史已传递给道具。

问题在于,在您的 PrivateRoute 中,您有一个名为 userLogged 的常量变量,它以值 false 启动。如果变量是true,则渲染定义的组件。如果是 false,则重定向到 /login

userLogged 的值始终是 false,因此您总是重定向到 /login。我建议您在父组件 App 中或通过使用 redux.

中的商店来处理 logged-in 状态

使用'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)基于此 "user" 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;