在 react + redux + react-router-redux 中导航到用户登录成功的主页

Posted

技术标签:

【中文标题】在 react + redux + react-router-redux 中导航到用户登录成功的主页【英文标题】:Navigate to Home page on User Login Success in react + redux + react-router-redux 【发布时间】:2017-11-17 16:51:02 【问题描述】:

应用需求是这样的:

1) 有一个简单的用户名和密码的登录表单 2)一旦用户提交登录表单,用户应该导航到主组件

为了做到这一点,我用 react-router-redux 配置了 redux

问题: 发送正确的用户名和密码后,服务器进行身份验证并发送正确的令牌,但现在我设法在 URL 中显示正确的路由,但组件没有加载,

这是我的文件

登录表单

import React,  Component  from 'react'
import  Button, Form, FormGroup, FormControl, ControlLabel, Checkbox, Col  from 'react-bootstrap';
import  bindActionCreators  from 'redux';
import  connect  from 'react-redux';
import  userAuthentication  from '../actions/userActions';


class LoginForm extends Component 

    constructor(props) 
        super(props)
        this.state = 
            email: '',
            password: ''
        
        this.onChange = this.onChange.bind(this);
        this.onFormSubmit = this.onFormSubmit.bind(this);
    


    onChange(e) 
        this.setState( [e.target.name]: e.target.value );
    

    onFormSubmit(e) 
        e.preventDefault();
        this.props.userAuthentication(this.state)
    

    render() 
        //const  user, token  = this.props.userState;
        const formInstance = (
            <div>
                /*token ? <p>token</p> : "null"*/
                <Form horizontal onSubmit=this.onFormSubmit>
                    <FormGroup controlId="formHorizontalEmail">
                        <Col componentClass=ControlLabel sm=2>
                            Email
                  </Col>
                        <Col sm=5>
                            <FormControl type="email" name="email" onChange=this.onChange value=this.state.email placeholder="Email" />
                        </Col>
                    </FormGroup>
                    <FormGroup controlId="formHorizontalPassword">
                        <Col componentClass=ControlLabel sm=2>
                            Password
                    </Col>
                        <Col sm=5>
                            <FormControl type="password" name="password" onChange=this.onChange value=this.state.password placeholder="Password" />
                        </Col>
                    </FormGroup>
                    <FormGroup>
                        <Col smOffset=2 sm=10>
                            <Checkbox>Remember me</Checkbox>
                        </Col>
                    </FormGroup>
                    <FormGroup>
                        <Col smOffset=2 sm=10>
                            <Button type="submit">
                                Sign in
                         </Button>
                        </Col>
                    </FormGroup>
                </Form>
            </div>
        );
        return (formInstance);
    



function mapDispatchToProps(dispatch) 
    return bindActionCreators( userAuthentication: userAuthentication , dispatch)


export default connect(null, mapDispatchToProps)(LoginForm);

动作

import  WS_URL  from '../utill/types';
import axios from 'axios';
import  push  from 'react-router-redux'

export function userAuthentication(userData)
    return function (dispatch) 
        dispatch(type: 'USER_LOGIN');
        axios.post(WS_URL+'/authenticate', 
        userData,
        headers:
            'Access-Control-Allow-Origin': '*'
         
        )
        .then(function (response)
          dispatch(type: 'USER_LOGIN_COMPLETED', payload: response.data)
           dispatch(push('/home'))
           //push('/home')
        )
        .catch(function (error)    
           dispatch(type: 'USER_LOGIN_REJECTECTED', payload: error)
        );
       

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import  Provider  from "react-redux"
import createHistory from 'history/createBrowserHistory'
import  Route  from 'react-router'
import  ConnectedRouter  from 'react-router-redux'
//import Routes from './js/utill/routes'
import registerServiceWorker from './registerServiceWorker';
import './css/index.css';
import store from "./store"
import App from './js/components/App';
import Home from './js/components/Home';
import LoginPage from './js/containers/LoginPage';

const history = createHistory()

ReactDOM.render( <Provider store=store> 
   <ConnectedRouter history=history>
        <div>
            <Route exact path="/" component=App/>
            <Route path="/login" component=LoginPage/>
            <Route path="/home" component=Home/>
        </div>
    </ConnectedRouter>
</Provider>
, document.getElementById('root'));
registerServiceWorker();

store.js

import  applyMiddleware, createStore  from 'redux'
import logger from 'redux-logger'
import  routerMiddleware,routerReducer  from 'react-router-redux';
import thunk from "redux-thunk"
import reducers from './js/reducers'
import createHistory from 'history/createBrowserHistory'
import  combineReducers  from 'redux'

const history = createHistory()

const combinedReducers = combineReducers(
    ...reducers,
    router: routerReducer
  )

const middleware = applyMiddleware(logger , thunk, routerMiddleware(history));

export default createStore(combinedReducers, middleware)  

依赖列表

"axios": "^0.16.2",
    "history": "^4.6.2",
    "react": "^15.6.0",
    "react-bootstrap": "^0.31.0",
    "react-dom": "^15.6.0",
    "react-facebook-login": "^3.6.1",
    "react-google-login": "^2.9.2",
    "react-redux": "^5.0.5",
    "react-router-redux": "^5.0.0-alpha.6",
    "redux": "^3.6.0",
    "redux-logger": "^3.0.6",
    "redux-promise": "^0.5.3",
    "redux-thunk": "^2.2.0"

有人可以帮我解释一下为什么这个路由不起作用,

【问题讨论】:

你有react-router-redux 的正确版本吗?最新版本好像是v4.1.1 here @stafamus 是的,这似乎是我安装它时最新的一个指向这个,我有同样的问题,似乎是 【参考方案1】:

我个人将“react-router”库与 react/redux 应用程序一起使用,它工作正常...

import  browserHistory  from 'react-router';

browserHistory.push('/home');

【讨论】:

我忘了你需要在使用 webpack 启动你的开发服务器时指定这个(如果你使用它):webpack-dev-server --history-api-fallback", 但是目前我们没有正确配置webpack,使用最新的react配置? 我不确定我是否收到了你的问题,但我只想提一下,我需要调整我的 webpack 开发服务器配置以使其正常工作

以上是关于在 react + redux + react-router-redux 中导航到用户登录成功的主页的主要内容,如果未能解决你的问题,请参考以下文章

如何在 mapStateToProps 中使用 useParams?

React 路由基本配置

在react项目当中使用redux

React+Redux学习笔记:React+Redux简易开发步骤

React-Router-Redux:在“react-router-redux”中找不到导出“syncHistoryWithStore”

在 react + redux + react-router-redux 中导航到用户登录成功的主页