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

Max*_*x P 30 javascript reactjs redux

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

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

用户名和密码从dumb-component到达.

智能组件连接

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

function mapDispatchToProps(dispatch) {
  return bindActionCreators(LoginActions, dispatch)
}
Run Code Online (Sandbox Code Playgroud)

如何从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
Run Code Online (Sandbox Code Playgroud)

Max*_*x P 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);
Run Code Online (Sandbox Code Playgroud)

  • 这里的关键是要意识到在mapStateToProps中,"state"不仅仅是对象的本地状态,而是redux应用程序的单一状态.我认为倾向于认为你可以只使用return {user:state.user},因为很可能{user:''}是你在本地获得的那个组件的动作,减少器等. (26认同)