我在两种不同的操作中有两种方法,

import { fetchCategories } from "../../../actions/elementsActions"
import { fetchPlaces } from "../../../actions/placesActions"


而且componentWillMount方法是:

componentWillMount() {
    this.props.dispatch(fetchCategories())
    this.props.dispatch(fetchPlaces())
}


我想确保在fetchPlaces之前获取fetchCategories。这是正确的做法吗?

更新

动作:



import axios from "axios";

export function fetchPlaces() {
  return function(dispatch) {
    axios.get("/getPlaces")
      .then((response) => {
          console.log(response);
        dispatch({type: "FETCH_PLACES_FULFILLED", payload: response.data})
      })
      .catch((err) => {
        dispatch({type: "FETCH_PLACES_REJECTED", payload: err})
      })
  }
}





减速机:



export default function reducer(
    state={
        places: [],
        fetching: false,
        fetched: false,
        error: null,
    }, action) {

    switch (action.type) {
      case "FETCH_PLACES": {
        return {...state, fetching: true}
      }
      case "FETCH_PLACES_REJECTED": {
        return {...state, fetching: false, error: action.payload}
      }
      case "FETCH_PLACES_FULFILLED": {

        return {
          ...state,
          fetching: false,
          fetched: true,
          places: action.payload,
        }
      }
    }

    return state
}





店铺:



import { applyMiddleware, createStore } from "redux"

import logger from "redux-logger"
import thunk from "redux-thunk"
import promise from "redux-promise-middleware"

import reducer from "./reducers"

const middleware = applyMiddleware(promise(), thunk, logger())

export default createStore(reducer, middleware)

最佳答案

调度是同步的,但这只能保证在fetchCategories之前触发(不提取)fetchPlaces。您需要从this.props.dispatch(fetchPlaces())中删除​​componentWillMount()并将其添加到then((response)fetchPlaces()中,以确保成功获取fetchPlaces()后将其触发。

09-17 20:06