如何使用react-redux连接mapStateToProps,MapDispatchToProps和redux-router

时间:2015-12-24 09:25:57

标签: javascript reactjs redux

我想在我的容器中使用" LoginPage" (智能组件)登录后重定向。 像这样:

handleSubmit(username, pass, nextPath) {
    function redirect() {
        this.props.pushState(null, nextPath);
    }
    this.props.login(username, pass, redirect); //action from LoginAcitons
  }

用户名和密码来自dumb-component。

智能组件连接

function mapStateToProps(state) {
  return {
    user: state.app.user
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(LoginActions, dispatch)
}

如何从redux-router添加pushState?或者我错了路?

export default connect(mapStateToProps, {pushState})(LoginPage); //works, but haven't actions

export default connect(mapStateToProps, mapDispatchToProps)(LoginPage); //works, but haven't pushState

export default connect(mapStateToProps, mapDispatchToProps, {pushState})(LoginPage); //Uncaught TypeError: finalMergeProps is not a function

2 个答案:

答案 0 :(得分:28)

function mapStateToProps(state) {
  return {
    user: state.app.user
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(LoginActions, dispatch),
    routerActions: bindActionCreators({pushState}, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginPage);

答案 1 :(得分:1)

简单的骨架:

import React from 'react';
import ReactDOM from 'react-dom'
import { createStore,applyMiddleware, combineReducers } from 'redux'
import { connect, Provider } from 'react-redux'
import thunk from 'redux-thunk'
import logger from 'redux-logger'

import View from './view';
import {playListReducer, artistReducers} from './reducers'


/*create rootReducer*/


const rootReducer = combineReducers({
  playlist: playListReducer,
  artist: artistReducers
})

/* create store */
let store = createStore(rootReducer,applyMiddleware(logger ,thunk));


/*  connect view and store   */
const App = connect(
  state => ({
    //same key as combineReducers
    playlist:state.playlist,
    artist:state.artist
  }),
  dispatch => ({

    })
  )(View);



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