【问题标题】:Navigate to other route if Redux action is finished (or failed)如果 Redux 操作完成(或失败),导航到其他路由
【发布时间】:2018-04-30 01:50:43
【问题描述】:

我的问题和这个问题差不多:React-Router: how to wait for an async action before route transition

现状:

例如,当我在我的主页上时,我会点击一个帖子(例如 /news/news-article)。我立即导航到该路线,并显示一个加载程序,直到我的 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);

所以我认为我走在正确的道路上,但我仍然无法让它发挥作用。它仍然会立即导航而不是延迟。

【问题讨论】:

  • 您的问题与您链接的问题有何不同?您从这些答案中尝试了什么,结果如何?
  • 另一个问题中给出的答案(与给我的答案几乎相同)由于某种原因对我不起作用。当我的操作FetchPost 收到数据时,我调用dispatch(push('/about/'))。现在,当我从主页导航到我的新闻帖子时,它立即导航到另一个 URL(例如 /news/newspost)并且我看到了一个加载器,当获取数据时,URL 从 /news/newspost 更改为 /about (因为我添加了 '/About/' 来测试它)。但除了 URL 更改之外,什么也没有发生。

标签: reactjs react-router react-redux react-router-v4


【解决方案1】:

这在 here 关于 react-redux 异步操作的详细信息中有很多介绍。但简而言之,其中一种方法是您可以使用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
    }
}

【讨论】:

  • 感谢您的回复!看到你的回答告诉我我快到了,但我还没有让它工作。我在我的问题中添加了一些代码,希望你能帮助我!
  • 推送从何而来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
  • 2021-10-19
  • 2021-10-16
  • 2018-05-03
  • 1970-01-01
  • 2016-08-17
相关资源
最近更新 更多