无法获取Redux分派函数

时间:2018-08-23 18:03:45

标签: reactjs redux redux-thunk

首先,我还是React / Redux领域的新手。

我在actions / index.js中执行以下操作

export function fetchLatestSchedule()
{
    //const uri = '/rest/schedule';
    console.log("Fetching latest schedule action");
    const uri = 'http://localhost:8585/MissionClockService/rest/schedule';
    return dispatch => {
        console.log("Fetching latest schedule action function");
        return fetch(uri)
        .then(response => {
            console.log("response: " + response);
            return response.json().then(body => ({ response, body }));}
        )
        .then(({ response, body }) => {
            console.log("Response from schedule fetch: " + body);
          if (!response.ok) {
            dispatch({
              type: SCHEDULE_REQUEST_FAILURE,
              payload: body.error
            });
          } else {
            dispatch({
              type: SET_CONTACTS,
              payload: body
            });
          }
        });
    }

}

我的商店是在store / index.js中创建的

import {createStore, combineReducers, applyMiddleware} from 'redux';
import reducers from '../reducers/index';
import thunk from 'redux-thunk';

const reducer = combineReducers(reducers);
const store = createStore(reducer, applyMiddleware(thunk));

export default store;

最后,我使用该操作的组件如下(MissionClockApp.js)

import React, { Component } from 'react';
import NextContactPanel from './NextContactPanel';
import CurrentContactPanel from './CurrentContactPanel';
import ConfigMenu from './components/ConfigMenu';
import FileModal from './components/FileModal';
import WebsocketConnection from './components/WebsocketConnection';
import {fetchDefaultConfig, fetchLatestSchedule} from './actions';
import {connect} from 'react-redux';

const mapDispatchToProp = dispatch => {
    return {
        fetchData: function(){
            console.log("Fetching data");
            dispatch(fetchDefaultConfig);
            dispatch(fetchLatestSchedule);
        }
    };
  }

class ConnectedMissionClockApp extends React.Component
{
    componentDidMount()
    {
        this.props.fetchData();
    }

    render()
    {
        return (<div>
            <ConfigMenu/>
            <NextContactPanel/>
            <CurrentContactPanel/>
            <FileModal/>
            <WebsocketConnection/>
        </div>);
    }
}

const MissionClockApp = connect(null, mapDispatchToProp)(ConnectedMissionClockApp);
export default MissionClockApp

当我在浏览器调试日志中查看时,看到的消息一直显示为“正在获取最新的调度操作”,但此后却什么也没有,并且我的REST服务在GET方法中没有任何请求。

我确定这确实是我最想念的东西,但是当查看类似https://redux.js.org/advanced/asyncactions之类的示例或其他SO帖子时,我似乎无法弄清楚我在做什么错。除了发生console.log和uri设置的dispatch(...)调用(我不在乎调度“发出请求”状态更改)之外,我的代码似乎与示例完全相同。 / p>

我在哪里弄糟了?

谢谢!

1 个答案:

答案 0 :(得分:2)

问题是您实际上没有正确地分发垃圾。

让我粘贴来自a gist I wrote demonstrating various forms of dispatching的示例:

// approach 1: dispatching a thunk function
const innerThunkFunction1 = (dispatch, getState) => {
    // do useful stuff with dispatch and getState        
};
this.props.dispatch(innerThunkFunction1);

// approach 2: use a thunk action creator to define the function        
const innerThunkFunction = someThunkActionCreator(a, b, c);
this.props.dispatch(innerThunkFunction);

// approach 3: dispatch thunk directly without temp variable        
this.props.dispatch(someThunkActionCreator(a, b, c));

// approach 4: pre-bind thunk action creator to automatically call dispatch
const boundSomeThunkActionCreator = bindActionCreators(someThunkActionCreator, dispatch);
boundSomeThunkActionCreator(a, b, c);

采用(dispatch, getState) => {}的函数是实际的thunk函数。外部函数是一个“ thunk action creator”,它返回thunk函数。

编写dispatch(fetchDefaultConfig);时,您是将 thunk动作创建者传递给dispatch,而不是 actual thunk函数本身

当thunk中间件看到某个功能通过管道进入时,它将运行该功能。因此,它试图运行您的动作创建者,并传递(dispatch, getState),但这将无法正常工作。

为使当前代码正常工作,它必须为dispatch(fetchDefaultConfig())。换句话说,请调用thunk动作创建者,然后将返回的thunk函数传递给dispatch

我个人将fetchData写为一个笨拙的东西,并使用“对象简写”将动作创建者传递给连接的组件,而不是在mapDispatch函数中这样做:

function fetchData() {
    return (dispatch) => {
        dispatch(fetchDefaultConfig());
        dispatch(fetchLatestSchedule());
    }
}

const mapDispatch = {fetchData};    

const MissionClockApp = connect(null, mapDispatch)(ConnectedMissionClockApp);