React redux - 好的url但不渲染组件

时间:2017-10-09 20:24:13

标签: reactjs redux react-router react-redux

在我的应用程序中,如果用户已登录,我有一个保存userData的状态,但我想将其重定向到/dashboard/:id并带有id。但是当动作完成时,url是好的(例如:/ dashboard / 12),但视图是/ login组件上的样式..

路由器版本:

"react-router": "^3.2.0",
"react-router-dom": "^4.2.2"

以下是代码:

App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Login from './components/Login/Login';
import Register from './components/Register/Register';
import Dashboard from './components/Dashboard/Dashboard';
import './App.css';

class App extends Component {
  render() {
    return (
        <Router>
                <div>
                    <Route path="/register" component={Register} />
                    <Route path="/login" component={Login} />
                    <Route path="/dashboard/:id" component={Dashboard} />
                </div>
        </Router>
    );
  }
}

export default App;

sessionReducer:

import * as types from '../actions/types';
import initialState from './initialState';

export default function sessionReducer(state = initialState, action) {
    switch(action.type) {
        case types.LOG_IN_SUCCESS:
        console.log(action);
            return {
                ...state,
                userData: action.payload
            }
        case types.LOG_IN_FAILED:
            console.log('login failed');
            break;
        default:
            return state;
    }
}

authAction.js:

import { browserHistory } from 'react-router';
import  { Redirect } from 'react-router-dom'
import * as types from './types';
import sessionApi from '../api/SessionApi';
import history from '../history';

export function loginSuccess(userData) {
    return {
        type: types.LOG_IN_SUCCESS,
        payload: userData
    }
}

export function loginFailed() {
    return {
        type: types.LOG_IN_FAILED
    }
}

export function logInUser(credentials) {
    return function(dispatch) {
        return sessionApi.login(credentials)
            .then(response => {
                console.log(response);
                if(response.data) {
                    sessionStorage.setItem('jwt', response.data.authentication_token);
                    dispatch(loginSuccess(response.data));
                    history.push('/dashboard/' + response.data.id);
                } else {
                    dispatch(loginFailed());
                }
            })
            .catch(error => {
                throw(error);
            })
    }
}

dashboard.js:

import React, { Component } from 'react';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';

class Dashboard extends Component {
    constructor(props) {
        super(props);
        console.log(props);
    }

    componentWillReceiveProps() {

    }

    render() {
        console.log(this.props.userData);
        return(
            <div>
                <h1> Hello user </h1>
            </div>
        );
    }
}

const mapStateToProps = (state) => { 
    return { 
        userData: state.sessionReducer.userData 
    } 
} 

export default withRouter(connect(mapStateToProps)(Dashboard));

和loginForm.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import { withRouter } from 'react-router'; 
import { connect } from 'react-redux';
import  * as authActions from '../../actions/authActions';


class LoginForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
            errors: {},
            isLoading: false,
        };
    }

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

    onSubmit(e) {
        e.preventDefault();
        this.setState({ errors: {}, isLoading: true });
        this.props.actions.logInUser( { data: { user: { email: this.state.email, password: this.state.password }}})
    }

    render() {
        return(
            <div>
                <form onSubmit={this.onSubmit.bind(this)}>
                    <div className="field">
                        <label className="label"> Email </label>
                        <div className="control">
                            <input type="email"
                                   name="email"
                                   value={this.state.email}
                                   onChange={this.onChange.bind(this)}
                                   className="input" />
                        </div>
                    </div>
                    <div className="field">
                        <label className="label"> Mot de passe </label>
                        <div className="control">
                        <input type="password"
                               ref="password"
                               name="password"
                               value={this.state.password}
                               onChange={this.onChange.bind(this)}
                               className="input" />
                        </div>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Signup" className="button is-primary" />
                    </div>
                    <Link to={{ pathname: '/register' }}>Inscription</Link>
                </form>
            </div>
        );
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(authActions, dispatch)
    };
}

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

我只想用正确的视图呈现好的组件,有人知道为什么Dashboard组件不呈现吗?

修改

添加index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { routerMiddleware } from 'react-router-redux'
import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from './reducer/rootReducer';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

/*
*   CSS
*/
import './bulma.css';
import './index.css';

/*
*   Render
*/

const store = createStore(
    rootReducer,
    compose(
        applyMiddleware(thunk),
        window.devToolsExtension ? window.devToolsExtension() : f => f
    )
);


ReactDOM.render(
    <Provider store={store}>
        <App /> 
    </Provider>,
    document.getElementById('root'));
registerServiceWorker();

1 个答案:

答案 0 :(得分:0)

你必须在路由器v4中使用:

<BrowserRouter>
  <Switch>
    <Route exact path="/testcolors" component={TestColors} />
  </Switch>
</BrowserRouter>


this.props.history.push('/customers');