登录后更改URL并且不显示视图(无重新加载,呈现页面) - 做出反应

时间:2017-10-25 21:42:52

标签: reactjs redux react-router-v4

我有一个登录反应类,在通过身份验证并成功通过身份验证后,应该将我带到管理页面,但在这种情况下,只需在成功登录或注销后将URL更改为管理页面,但不会显示任何内容新的管理组件。我正在使用react-router v4,这个应用程序不能很好地使用它。这是我的组件 也许有办法解决这个问题。我使用高阶组件withRouter来解决这个问题,但它没有做任何事情。我在控制台中没有错误。

Sign In

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {reduxForm, Field} from 'redux-form';
import {withRouter} from 'react-router-dom';
import * as actions from '../../actions/signin_user';


class SignIn extends Component {
    handleFormSubmit({email, password}) {
        this.props.signinUser({email, password});    
    }

    renderAlert() {
        if (this.props.errorMessage) {
            return (
                <div className="alert alert-danger">
                    <strong>Oops! Błąd logowania, kod błędu: {this.props.errorMessage}</strong>
                </div>
            )
        }
    }


    render() {
        const {handleSubmit, fields: {email, password}} = this.props;
        return (
            <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
                <fieldset className="form-group">
                    <label>Adres Email:</label>
                    <Field {...email} name="email" type="text" className="form-control" component="input"/>
                </fieldset>
                <fieldset className="form-group">
                    <label>Hasło:</label>
                    <Field {...password} name="password" type="password" className="form-control" component="input"/>
                </fieldset>
                {this.renderAlert()}
                <button action="submit" className="btn btn-primary">Zaloguj się</button>
            </form>
        )
    }
}

function mapStateToProps(state) {
    return {errorMessage: state.auth.error}
}

SignIn = reduxForm({form: 'SignIn', fields: ['email', 'password']})(SignIn);

export default withRouter(connect(mapStateToProps, actions)(SignIn));

管理页面

/**
 * Created by konraduciechowski on 26.08.2017.
 */
import React, {Component} from 'react';

import {Link} from 'react-router-dom';


class AdminPage extends Component {
    render() {

        return (
            <div className="header-stick">
                {/*IMPORTANT ADD FUNCTION TO NOT ABLE EVERYONE TO GET TO ADMIN PAGE
                 WHEN THEIR NOT ADMIN*/}
                {/*NEED TO FIX ROUTES FOR ADMIN PAGE*/}
                <ul className="admin-menu">
                    <li className="admin-menu-item">
                        <Link to="/panel+administracyjny/kalendarz">Kalendarz</Link>
                    </li>
                    <li className="admin-menu-item">
                        <Link to="/panel+administracyjny/blog">Blog</Link>
                    </li>
                    <li className="admin-menu-item">
                        <Link to="/panel+administracyjny/pracownik">Zarządzanie pracownikami</Link>
                    </li>
                </ul>

            </div>
        )
    }
}

export default AdminPage;

redux行动

/**
 * Created by konraduciechowski on 16.10.2017.
 */
import axios from 'axios';
import history from '../helpers/history';
import {AUTH_USER, AUTH_ERROR, UNAUTH_USER} from './types'

const ROOT_DEV_API = 'http://salonenface.dev/api/';
const ROOT_PROD_API = 'https://salonenface.pl/api/';
const ROOT_TEST_API = 'http://localhost:3090';


export function signinUser({email, password}) {
    return function (dispatch) {

//Submit password n' email to server
        axios.post(`${ROOT_TEST_API}/signin`, {email, password})
            .then(response => {
                //    if request is good...

                //    Update state to indicate user is authenticated
                dispatch({type: AUTH_USER});
                //    Save JWT token
                localStorage.setItem('token', response.data.token);
                //    redirect to admin route section
                history.push("/panel+administracyjny");
            })
            .catch((error) => {
                ///////////////////////////////////////////
                //    if request is bad...

                //  show error to user
                dispatch(authError(error.response.status));
            })
    }

}

export function signupUser({email, password}) {
    return function (dispatch) {
        axios.post(`${ROOT_TEST_API}/signup`, {email, password})
            .then(response => {
                dispatch({type: AUTH_USER});
                localStorage.setItem('token', response.data.token);
                history.push('/panel+administracyjny');
            })
            .catch(error => dispatch(authError(error.response.data.error)))
    }
}

export function authError(error) {
    return {
        type: AUTH_ERROR,
        payload: error
    }
}

export function signoutUser() {
    localStorage.removeItem('token');
    return {type: UNAUTH_USER}
}

编辑:

Router.js

//React imports
import React, {Component} from 'react';
import {
    BrowserRouter as Router,
    Route,
    Switch,
    Redirect,
    withRouter
} from 'react-router-dom';

//Redux imports
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import promise from 'redux-promise';
import reduxThunk from 'redux-thunk';

//Css imports
import '../styles/App.css';
import '../styles/Admin.css';
import '../../node_modules/bootstrap/dist/css/bootstrap.css';
import '../../node_modules/font-awesome/css/font-awesome.css';
import '../../node_modules/react-big-calendar/lib/css/react-big-calendar.css';

//Page Components imports
import Header from './SiteElementsComponents/Header';
import About from './MainComponents/About';
import Blog from './MainComponents/Blog';
import BlogPost from './MainComponents/BlogPost';
import Contact from './MainComponents/Contact';
import Home from './MainComponents/Home';
import Order from './CalendarComponents/Order';
import Services from './MainComponents/Services';
import Login from './AuthComponents/Login';
import Register from './AuthComponents/Register';
import Footer from './SiteElementsComponents/Footer';
import OrderComplete from './CalendarComponents/OrderComplete';
import SignIn from './AuthComponents/SignIn';
import SignOut from './AuthComponents/SignOut';
import SignUp from './AuthComponents/SignUp';

//Admin Components imports
import AdminPage from './AuthComponents/AdminComponents/AdminPage';
import AdminCalendar from './AuthComponents/AdminComponents/AdminCalendar';
import AdminBlog from './AuthComponents/AdminComponents/AdminBlog';
import AdminBlogNewPost from './AuthComponents/AdminComponents/AdminBlogNewPost';
import AdminBlogShowPost from './AuthComponents/AdminComponents/AdminBlogShowPost';
import AdminEmployee from './AuthComponents/AdminComponents/AdminEmployee';
import AuthExample from './TestComponents/AuthExample';

//Redux reducers
import reducers from '../reducers';

//History
import history from '../helpers/history';

//Middleware
const createStoreWithMiddleware = applyMiddleware(promise, reduxThunk)(createStore);

const App = () => {

        return (
            <Provider store={createStoreWithMiddleware(reducers)}>
                <div>
                    <div className="col-xs-12">
                        <Router history={history}>
                            <div>
                                <Header/>
                                <div className="container background-block">
                                    <Switch>
                                        <Route exact path="/" component={Home}/>
                                        <Route path="/o+nas" component={About}/>
                                        <Route path="/aktualnosci" component={Blog}/>
                                        <Route path="/post/:id" component={BlogPost}/>
                                        <Route path="/kontakt" component={Contact}/>
                                        <Route path="/uslugi" component={Services}/>
                                        <Route path="/logowanie" component={Login}/>
                                        <Route path="/signin" component={SignIn}/>
                                        <Route path="/wylogowanie" component={SignOut}/>
                                        <Route path="/signup" component={SignUp}/>
                                        <Route path="/rejestracja" component={Register}/>
                                        <Route path="/wizyta+zapisana" component={OrderComplete}/>
                                        {/*Calendar options*/}
                                        <Route path="/wizyta+zapisana" component={OrderComplete}/>
                                        <Route path="/wizyta" component={Order}/>
                                    </Switch>
                                    {/*test options*/}
                                    <Route exact path="/AuthExample" component={AuthExample}/>
                                    {/*/!*admin options*!/*/}
                                    <Switch>
                                        <Route exact path="/panel+administracyjny" component={AdminPage}/>
                                        <Route path="/panel+administracyjny/kalendarz" component={AdminCalendar}/>
                                        {/*admin blog options*/}
                                        <Route path="/panel+administracyjny/blog" component={AdminBlog}/>
                                        <Route path="/panel+administracyjny/post/nowy" component={AdminBlogNewPost}/>
                                        <Route path="/panel+administracyjny/pokaz+post/:id"
                                               component={AdminBlogShowPost}/>
                                        {/*admin employee options*/}
                                        <Route path="/panel+administracyjny/pracownik" component={AdminEmployee}/>
                                    </Switch>
                                </div>
                            </div>
                        </Router>
                        <Footer/>
                    </div>
                </div>
            </Provider>
        );

}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Router';
import registerServiceWorker from './registerServiceWorker';
import './styles/index.css';

ReactDOM.render(<App />, document.getElementById('app'));
registerServiceWorker();

1 个答案:

答案 0 :(得分:2)

  

您无法将历史记录传递给<BrowserRouter>,因为它会创建历史记录   自己的历史对象

如果您要创建自己的历史记录,请使用<Router>代替<BrowserRouter>,然后传递历史记录对象

Import { Router } from 'react-router-dom'
<Router history={history}> <Router/>

您可以在react-router v.4

上阅读更多内容