我或多或少有与此问题相同的问题:React-Router: how to wait for an async action before route transition
现状:
当我在我的主页上时,我点击了一个帖子(例如/ news / news-article)。我立即导航到路线,我正在展示一个Loader,直到我的Redux动作已经获取帖子内容,然后我加载内容。 (这也是'jmancherje'在另一个问题中回答的问题)
但这意味着我必须在用户访问的每个页面上显示一个加载器,这不是我想要的。
所以我想要的是:
当我在家中时,我点击其他帖子,我想等到导航到下一条路线,直到我的动作完成(或失败)加载内容。
这似乎可以用React-Router-Redux,但我无法找到如何实现这一点。
更新了问题:
我的行动如下:
export function fetchPage(post_type, postSlug) {
return function (dispatch) {
dispatch({type: FETCH_PAGE_START});
axios.get(`${url}/wp-json/wp/v2/${post_type}?slug=${postSlug}`)
.then(response => {
dispatch({
type: FETCH_PAGE,
payload: response.data
});
dispatch(push('/')) // do the routing here
})
.catch(function (error) {
dispatch({
type: FAILED_PAGE
});
});
}
}
我的商店或多或少看起来像这样:
const appliedMiddleware = applyMiddleware( thunk, createLogger(), routerMiddleware(history));
export default createStore(combinedReducers, appliedMiddleware);
所以我认为我的方式正确,但仍然无法让它发挥作用。它仍然会立即导航而不是延迟。
答案 0 :(得分:0)
有关react-redux异步操作的详细信息here中详细介绍了这一点。但简而言之,其中一种方法是使用redux-thunk中间件:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// Note: this API requires redux@>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
一旦你拥有了redux-thunk中间件,你可以在 action_post.js 中执行以下操作:
export function fetchPost(id) {
return dispatch => {
dispatch(fetchPostRequest())
axios.get(`/api/post/${id}`)
.then(res => {
dispatch(fetchPostSuccess(res.data))
dispatch(push('/postView')) // do the routing here
})
.catch(err => {
dispatch(fetchPostFailure(err))
})
}
}
function fetchPostRequest() {
return {
type: "FETCH_POST_REQUEST"
}
}
function fetchPostSuccess(data) {
return {
type: "FETCH_POST_SUCCESS",
data
}
}
function fetchPostFailure(err) {
return {
type: "FETCH_POST_FAILURE",
err
}
}