1
我有兩個不同的動作兩種方法,多分派陣營
import { fetchCategories } from "../../../actions/elementsActions"
import { fetchPlaces } from "../../../actions/placesActions"
而且componentWillMount方法是:
componentWillMount() {
this.props.dispatch(fetchCategories())
this.props.dispatch(fetchPlaces())
}
我要確保fetchCategories是fetchPlaces前牽強。這是做這件事的正確方法嗎?
UPDATE
操作:
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)
我認爲派遣是默認同步的,所以是的,它應該工作。但是,設置狀態可能並不總是如此。你有沒有試過運行你的代碼,看看它是否工作? –
@KeithA是的,在componentWillReceiveProps中,我正在檢查nextProps是否具有這兩個值,然後設置狀態。 –
你介意發佈行動創作者和減速器嗎? –