簡體   English   中英

如何將redux-router的push方法添加到動作

[英]How to add push method from redux-router to actions

我正在嘗試在操作中從redux-router添加push方法。 當我執行動作時,請在有效負載中推送接收對象,但不要更改頁面。 在此處輸入圖片說明

動作/ index.js

 import { push } from 'redux-router'; export const actions = {}; actions.goTo = () => { return (dispatch) => { dispatch(push('/staff')); }; }; 

但是,如果我不是從動作中發起push ,而是從組件中直接push ,它就可以正常工作。

為MyComponent / 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> ); } } 

因此, push()可能僅在連接的組件內部起作用。 如果要從actions/index.js文件中使用它,則可以將其作為參數傳遞並在其中調用,而無需導入。 您可以有類似以下內容:

export const actions = {};

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

並從您的組件中將其稱為actions.goTo('staff', push)

編寫中間件時可能出錯。

注意:路由器中間件應在Logger中間件之后。

像這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM