【问题标题】:How to add push method from redux-router to actions如何将来自 redux-router 的推送方法添加到操作
【发布时间】:2017-02-16 22:57:55
【问题描述】:

我正在尝试将 push 方法从 redux-router 添加到操作中。 当我启动操作时,推送接收有效负载中的对象,但不要更改页面。 enter image description here

actions/index.js

import { push } from 'redux-router';

export const actions = {};

actions.goTo = () => {
    return (dispatch) => {
        dispatch(push('/staff'));
    };
};

但是如果我不是从动作中初始化push,而是直接在组件中它可以正常工作。

我的组件/index.js

import { push } from 'redux-router';
import { connect } from 'react-redux';

@connect((state) => ({}))
export default class MyComponent extends Component {

constructor (props) {
        super(props);
        this._goTo = ::this._goTo;
    }
    
_goTo (event) {
        event.preventDefault();
        const { dispatch } = this.props;
        dispatch(push('/staff'));
    }
    
    render () {
        return (
            <section>
              <button onClick = { this._goTo }>from component</button>
            </section>
        );
    }
}

【问题讨论】:

    标签: javascript reactjs redux redux-router


    【解决方案1】:

    编写中间件时可能会出错。

    注意:路由器中间件应该跟在 Logger 中间件之后。

    喜欢这个:

    compose(
        applyMiddleware(...middleware),
        reduxReactRouter({ createHistory })
    );
    

    【讨论】:

      【解决方案2】:

      因此,push() 只能在连接的组件内部工作。如果您想从 actions/index.js 文件中使用它,您可以将它作为参数传递并在那里调用它,而无需导入它。你可以有类似的东西:

      export const actions = {};
      
      actions.goTo = (route, push) => {
          return () => {
              push(`/${route}`);
          };
      };
      

      并从您的组件中将其称为actions.goTo('staff', push)

      【讨论】:

      • 我试过这个我在replaceRoutesMiddleware.js Uncaught TypeError: Cannot read property 'type' of undefined收到这个错误
      猜你喜欢
      • 2018-07-24
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 2020-10-31
      • 2016-09-06
      • 1970-01-01
      • 2015-12-05
      相关资源
      最近更新 更多