Redux Thunk - 为什么我必须两次调用dispatch()?

Zac*_*ame 0 reactjs redux redux-thunk

注意我打电话setStepPositionIndex()dispatch().当我删除dispatch(...)成为正义setStepPositionIndex() 我会期望内部的调度调用setStepPositionIndex()将接收它传递的普通操作对象并发送它...

或者,如果我在显式返回其中的内部删除dispatch()调用setStepPositionIndex()(并保持dispatch(setStepPositionIndex())actionObj,我希望成功调度dispatch(setStepPositionIndex(actionObj))

但是这个动作创作者的成功执行需要两个......为什么?

   /* actions.js */
import { store } from "../store.js";

store.dispatch(setStepPositionIndex());

export const SET_STEP_POSITION_INDEX = "SET_STEP_POSITION_INDEX";
export const setStepPositionIndex = () => {
  return (dispatch, getState) => {
    const newSteps = getState().goals.currentGoalSteps.map((stepObj, index) => {
      return { ...stepObj, positionIndex: index };
    });
    console.log("newSteps", newSteps);
    /* [{step: "Step3", positionIndex: 0}
      {step: "Step2", positionIndex: 1}
      {step: "Step1", positionIndex: 2}] */

    const actionObj = {
      type: SET_STEP_POSITION_INDEX,
      stepsArr: newSteps
    };
    // Unsuccessful alone ->
    // return actionObj

    // unsuccessful alone (removing dispatch() wrapper from setStepPositionIndex
    //->
    return dispatch(actionObj);
  };
};

/*Reducer.js*/

import * as actions from "../Actions/actions";
import { store } from "../store";
if (action.type === "SET_STEP_POSITION_INDEX") {
  return update(state, {
    currentGoalSteps: { $set: action.stepsArr }
  });
}

/*Store.js */
import { createStore, applyMiddleware, compose, combineReducers } from "redux";
import { ApolloClient } from "react-apollo";
import { createLogger } from "redux-logger";
import { reducer as formReducer } from "redux-form";
// import { client } from './index'
import thunk from "redux-thunk";
import * as Goal_Reducer from "./Reducers/Global_Reducer";

const logger = createLogger({
  collapsed: (getState, action, logEntry) => !logEntry.error,
  predicate: (getState, action) => !action.type.includes("@@redux-form")
});

const client = new ApolloClient();

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export const store = createStore(
  combineReducers({
    goals: Goal_Reducer.goalReducer,
    apollo: client.reducer(),
    form: formReducer
  }),
  {}, //initial state
  composeEnhancers(applyMiddleware(client.middleware(), thunk, logger))
);
Run Code Online (Sandbox Code Playgroud)

And*_*Ray 6

哦,你只是在问你为什么要做store.dispatch(setStepPositionIndex());,仍然dispatch()在你的thunk里面.因为store.dispatch()是使用正确的参数调用内部返回的thunk函数的原因,并且dispatch()thunk内部是将操作传播到reducers的内容.我可以看到这对新手来说会有多奇怪,因为dispatch()它做了两件不同的事情.

首先你派遣thunk,然后thunk调度动作.

原始答案

使用时redux-thunk,让动作创建者返回一个函数(return (dispatch, getState) => {),则必须手动调用dispatch().你不能简单地从内部函数返回.这就是redux-thunk手动控制调度的重点.

如果您不想这样做,而不是使用getState(),您只需从组件中调度您的操作goalscurrentGoalSteps作为参数传入.