【问题标题】:How use react-redux connect with mapStateToProps,MapDispatchToProps and redux-router如何使用 react-redux 连接 mapStateToProps、MapDispatchToProps 和 redux-router
【发布时间】:2015-12-24 09:25:57
【问题描述】:

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

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

用户名和密码来自哑组件。

智能组件连接

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

【问题讨论】:

  • 我遇到了类似的问题。 LoginActions 这里是什么?
  • 为什么这需要在组件本身中完成?只是好奇。

标签: javascript reactjs redux


【解决方案1】:
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);

【讨论】:

  • 这里的关键是意识到在 mapStateToProps 中,“状态”不仅仅是对象的本地状态,而是 redux 应用程序的单一状态。我认为倾向于认为您可以只使用 return { user: state.user } 因为 { user: '' } 很可能是您在该组件的操作、reducers 等本地拥有的内容。
  • @netpoetica 谢谢!这在 redux 文档中没有得到强调,我对同样的事情感到困惑。当然,我可能浏览得太快了 XD
【解决方案2】:

简单的骨架:

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'));

【讨论】:

    猜你喜欢
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2018-06-15
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多