【问题标题】:Unable to fetch in redux dispatch function无法在 redux 调度功能中获取
【发布时间】:2018-08-23 18:03:44
【问题描述】:

首先,我还是 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(...) 调用(我不关心调度“发出请求”状态更改)之外,我的代码似乎与示例几乎相同。

我在哪里搞砸了?

谢谢!

【问题讨论】:

    标签: reactjs redux redux-thunk


    【解决方案1】:

    问题在于您实际上并未正确分派 thunk。

    让我粘贴来自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) =&gt; {} 的函数是实际的thunk 函数。外部函数是一个“thunk action creator”,它返回 thunk 函数。

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

    当 thunk 中间件看到一个函数通过管道时,它会运行该函数。所以,它试图运行你的动作创建器,并传入(dispatch, getState),但这是行不通的。

    要使您当前的代码正常工作,它需要是dispatch(fetchDefaultConfig())。也就是说,调用thunk action creator,并将返回的thunk函数传递给dispatch

    就我个人而言,我会将fetchData 本身写成一个thunk,并使用“对象速记”将动作创建者传递给连接的组件,而不是在mapDispatch 函数中执行:

    function fetchData() {
        return (dispatch) => {
            dispatch(fetchDefaultConfig());
            dispatch(fetchLatestSchedule());
        }
    }
    
    const mapDispatch = {fetchData};    
    
    const MissionClockApp = connect(null, mapDispatch)(ConnectedMissionClockApp);
    

    【讨论】:

    • 谢谢先生!那成功了,你的解释很棒。我是一名长期的 Java 开发人员,自 2003 年左右以来就没有使用过 JavaScript,因此学习所有新的语法和概念对我的旧大脑来说有点费力。感谢您的帮助!
    • 当然,很高兴有帮助!是的,如果您自 2003 年以来还没有使用过 JS,那么它是一种完全 不同的语言和生态系统。您可能对我的getting started with Reactgetting started with Redux 资源列表以及我的React/Redux links list 感兴趣。
    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 2019-10-16
    • 1970-01-01
    相关资源
    最近更新 更多