gpt4 book ai didi

javascript - componentWillMount React 中的多次分派(dispatch)

转载 作者:行者123 更新时间:2023-11-29 17:53:14 26 4
gpt4 key购买 nike

我在两个不同的 Action 中有两个方法,

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

componentWillMount 方法是:

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

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

更新

Action :

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})
})
}
}

reducer :

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)

最佳答案

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

关于javascript - componentWillMount React 中的多次分派(dispatch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41449078/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com