javascript - redux-thunk:暂停组件执行直到 Action Creator 完成

标签 javascript reactjs redux react-redux redux-thunk

几个星期以来,我一直在为这个问题而苦苦挣扎。我终于认输并寻求帮助,因为我显然没有做正确的事情。我有一个使用 redux 和 redux-thunk 的 React.js 应用程序。我只是想让我的组件容器启动数据加载,但在数据从获取请求返回之前不呈现。看起来很简单我知道。这是我所做的:

容器组件

'use strict';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchActivePlayer } from '../actions/index';
import PlayerDetails from '../components/players/player-detail';
import Spinner from '../components/common/spinner/index';
import store from '../store';

export default class PlayerDetailContainer extends Component {
    constructor(props) {
        super(props);
    }

    componentWillMount() {
        this.props.fetchActivePlayer(this.props.params.player_slug)
    }

    render() {
        if (!this.props.activePlayer.activePlayer) {
            return (
                <Spinner text="Loading..." style="fa fa-spinner fa-spin" />
            );
        }

        return (
            <PlayerDetails 
                player={ this.props.activePlayer.activePlayer } 
            />
        );
    }
}

function mapStateToProps(state) {
    return {
        activePlayer: state.activePlayer
    }
}
export default connect(mapStateToProps, { fetchActivePlayer })(PlayerDetailContainer);

Action 创作者

export function fetchActivePlayer(slug) {
    return (dispatch, getState) => {
        return axios.get(`${ROOT_URL}/players/${slug}`)
        .then(response => {
            dispatch({
                type: FETCH_ACTIVE_PLAYER,
                payload: response
            })
        })
        .catch(err => {
            console.error("Failure: ", err);
        });    
    };
}

商店

'use strict';
import React from 'react';
import { browserHistory } from 'react-router';
import { createStore, applyMiddleware } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import promise from 'redux-promise';
import reducers from './components/reducers/index';

const createStoreWithMiddleware = applyMiddleware(
    thunk,
    promise,
    routerMiddleware(browserHistory)
) (createStore);
export default createStoreWithMiddleware(reducers);

路线

export default (
<Route path="/" component={ App }>
        <IndexRoute component={ HomePage } />
        <Route path="players/:player_slug" component={ PlayerContainer } />
        <Route path="/:player_slug" component={ PlayerContainer } />
    </Route>
);

以下是我用于所有内容的版本: react = 0.14.7 react 还原= 4.4.1 redux-thunk = 0.5.3

当我运行它时,我没有收到任何错误,但很明显我的 Action 创建者正在触发,但我的组件容器继续运行而不是等待创建者完成。就像我说的,我确定我一定遗漏了一些非常简单的东西,但我似乎无法弄清楚那是什么。

提前致谢。任何帮助将不胜感激。

最佳答案

  1. 您在 componentWillMount 中的操作(获取)是异步的,组件不会等待。
  2. 通常当您获取一些数据时,您想了解获取过程的状态。像“isfetching”以显示加载程序,成功和失败以显示错误。
  3. 您可以使用这些状态不加载/安装/启动组件,直到 Action Creator 完成。

因此,你应该像这样组织你的 redux 部分:

状态

activePlayer:{
    data:data,
    isFetching: true/false,
    error:""
    }

Action

export const fetchActivePlayer = slug => dispatch =>{
    dispatch({
        type: 'FETCH_ACTIVE_PLAYER_REQUEST',
        isFetching:true,
        error:null
    });

    return axios.get(`${ROOT_URL}/players/${slug}`)
    .then(response => {
        dispatch({
            type: 'FETCH_ACTIVE_PLAYER_SUCCESS',
            isFetching:false,
            payload: response
        });
    })
    .catch(err => {
        dispatch({
            type: 'FETCH_ACTIVE_PLAYER_FAILURE',
            isFetching:false,
            error:err
        });
        console.error("Failure: ", err);
    });

};

reducer

const initialState = {data:null,isFetching: false,error:null};
export const actionPlayer = (state = initialState, action)=>{
    switch (action.type) {
        case 'FETCH_ACTIVE_PLAYER_REQUEST':
        case 'FETCH_ACTIVE_PLAYER_FAILURE':
        return { ...state, isFetching: action.isFetching, error: action.error };

        case 'FETCH_ACTIVE_PLAYER_SUCCESS':
        return { ...state, data: action.payload, isFetching: action.isFetching,
                 error: null };
        default:return state;

    }
};

那么你的组件可能看起来像这样(硬编码)

class PlayerDetailContainer extends Component {
    componentWillMount() {
        this.props.fetchActivePlayer(this.props.params.player_slug)
    }
    render() {
        if (this.props.isFetching) {
            return <Spinner text="Loading..." style="fa fa-spinner fa-spin" />

        }else if (this.props.error) {
            return <div>ERROR {this.props.error}</div>
        }else {
            return <PlayerDetails  player={ this.props.data }  />
        }
    }
}
const mapStateToProps = state =>({
        isFetching: state.activePlayer.isFetching,
        data: state.activePlayer.data,
        error: state.activePlayer.error,
})

我不知道您的应用程序是什么样的。此示例的目的是说明方法。

关于javascript - redux-thunk:暂停组件执行直到 Action Creator 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38064688/

相关文章:

javascript - 使用动态上下文数据时如何用新的 React context api 替换旧的 React contextTypes?

javascript - 使用 Redux 在 React 中调度 Action 的问题

javascript - jQuery 仅序列化表单的一部分

javascript - 带有选择选项的 jquery 事件问题

javascript - Facebook JS SDK : "(#100) No permission to publish the video" error

reactjs - Expo React Native App + Redux-Persist : AsyncStorage Problem

javascript - uploadcare 在reactjs应用程序中未定义

javascript - 函数 setState 中的事件目标为 null

javascript - prop `store.subscribe` 标记为必填

javascript - 在 Javascript Webpack 项目中过渡到 Typescript(如何导出模块)