可以这样做吗? (调度店)Redux

时间:2018-03-02 09:13:57

标签: reactjs redux react-redux

我有一个问题。 例如,我有以下代码:

//操作

 export function getNews () {
   return Api.getNews()
       .then((response) => {
       if (typeof response !== 'undefined') {
        return MainStore.dispatch(NewsActionCreators.getNews(response));
       }
     })
     .catch((error) => // some logic);
}

// ActionsCreator

import { NewsConstants } from 'front/constants/NewsConstants';

import { Action } from 'redux-actions';

export function getNews(payload): Action {
    return {
        type: NewsConstants.NEWS_RECEIVED,
        payload,
    };
}

//元器件

import * as NewsActions from 'front/actions/NewsActions';

componentDidMount() {
    getNews();
}

const mapStateToProps = (state, ownProps) => {
   return {
       news: state.News.getIn(['news']),
   };
};

const mapDispatchToProps = (dispatch, ownProps) => {
    return {};
};

// MainStore

import {applyMiddleware, createStore, Store} from 'redux';
import { routerMiddleware } from 'react-router-redux';
import createBrowserHistory from 'history/createBrowserHistory';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

import { Reducers} from 'front/reducers/index';
import promiseMiddleware from 'redux-promise-middleware';

const history = createBrowserHistory();
let middleware;

if (process.env.NODE_ENV !== 'production') {
    middleware = applyMiddleware(promiseMiddleware(), routerMiddleware(history), logger, thunk);
} else {
    middleware = applyMiddleware(promiseMiddleware(), routerMiddleware(history), thunk);
}

export const MainStore:Store<any> = createStore<any>(
    Reducers,
    middleware,
);

这很好用。但我只是想知道这是正确的方法吗?或者我需要通过组件内的 mapDispatchToProps 调用所有操作? 谢谢:))

更新。添加了MainStore

2 个答案:

答案 0 :(得分:3)

您应该通过mapDispatchToProps将动作创建者作为道具传递给组件:

componentDidMount() {
    this.props.getNews();
}

...

const mapDispatchToProps = dispatch => ({getNews: () => dispatch(getNews())})

答案 1 :(得分:1)

Miguel已经回答了你的问题。但我认为更好的方法是处理mapDispatchToProps,这里有值得一提:你可以将这些动作创建者直接传递给react-redux连接函数,如下所示:{ actionCreator1, actionCreator2 },或者你可以导入所有的动作创建者{{1然后将它们传播到连接函数中,如import * as newActions

{ ...newActions }

希望这有帮助!