反应,反应 - 还原延迟状态更新。如何处理?

时间:2017-05-28 14:55:54

标签: reactjs react-redux state transitions

使用reactjs与redux和react-router,redux-thunk我遇到状态更新问题。

有一些路线,我显示单个帖子,并从这个页面调用另一个帖子,我有一个延迟,旧状态显示,直到新状态更新。

我有post reducer

import * as types from '../actions/actionTypes';
import initialState from './initialState';

export default function sessionReducer(state = initialState.post, action) {
    switch(action.type) {
        case types.POST_SUCCESS:
            return action.post
        case types.ERROR:
            return null;
        default:
            return state;
    }
}

在这里我的行动

import * as types from './actionTypes';
import axios from 'axios';

if (process.env.NODE_ENV === 'development') {
    var postEndPoint = 'http://dev.test.com/wp-json/wp/v2/posts?slug=';
} else {
    var postEndPoint = 'http://prod.com/wp-json/wp/v2/posts?slug=';
}

export function getPost (slug) {
    return dispatch => {
        dispatch(setLoadingState()); // Show a loading spinner

        axios.all([
            axios.get(postEndPoint + slug)
        ]).then(axios.spread(function ( post) {
                dispatch(setPost(post.data))
                dispatch(doneFetchingData(post.data))

            }))
            .catch(error => {
                console.log(error)
                dispatch(showError(error))
            });
    }
}

function setPost(post) {
    return {
        type: types.POST_SUCCESS,
        post: post
    }
}

function setLoadingState() {
    return {
        type: types.SHOW_SPINNER,
        loaded: false
    }
}

function doneFetchingData( post) {
    return {
        type: types.HIDE_SPINNER,
        loaded: true,
        post: post
    }
}

function showError(error) {
    console.log(error)
    return {
        type: types.SHOW_ERROR,
        loaded: false,
        error: error
    }
}

我如何处理这个问题或我做错了什么?

0 个答案:

没有答案