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

时间:2017-06-15 09:06:01

标签: reactjs redux react-router-redux

申请要求如下:

1)使用简单的用户名和密码登录表单 2)用户提交登录表单后,用户应导航至主页组件

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

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

这是我的档案

LoginForm

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"

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

1 个答案:

答案 0 :(得分:0)

我个人使用带有react / redux应用程序的'react-router'库,它运行正常......

import { browserHistory } from 'react-router';

browserHistory.push('/home');