【问题标题】:React Redux how to dispatch async actions and update stateReact Redux 如何调度异步操作和更新状态
【发布时间】:2017-02-19 14:53:22
【问题描述】:

我尝试在我的学习 react,redux 项目中处理 ajax 数据,但我不知道如何调度一个动作并在组件内设置状态

这是我的组件

import React, {PropTypes, Component} from 'react';
import Upload from './Upload';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as profileActions from '../../../actions/profileActions';


class Profile extends Component {

    static propTypes = {
        //getProfile: PropTypes.func.isRequired,
        //profile: PropTypes.object.isRequired,
    };

    constructor(props) {
        super(props);

        this.state = {
            profile:{
                username: '',
                password: ''
            }
        }
        this.onUpdate = this.onUpdate.bind(this)
    }

    onUpdate(event) {
        alert()
    }

    componentWillMount() {
    }

    componentDidMount() {
    }


    render() {

        const {profile} = this.props;
        return (
            <div>

            </div>
        );
    }
}

function mapStateToProps(state) {
    console.log(state)
    return {
        profile: state.default.profile,
    };
}

function mapDispatchToProps(dispatch, ownProps) {
    return {
        actions: bindActionCreators(profileActions, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Profile);

我按照以下方式创建商店

import { createStore, combineReducers, applyMiddleware } from 'redux'
import createLogger from 'redux-logger'
import thunk from 'redux-thunk'
import { routerReducer, routerMiddleware, push } from 'react-router-redux'
import reducers from '../reducers'
import { browserHistory } from 'react-router';

const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
    middleware.push(createLogger());
}

middleware.push(routerMiddleware(browserHistory));

// Add the reducer to your store on the `routing` key
const store = createStore(
    combineReducers({
        reducers,
        routing: routerReducer
    }),
    applyMiddleware(...middleware),

)

export default store;

减速器

export const RESOLVED_GET_PROFILE = 'RESOLVED_GET_PROFILE'

const profileReducer = (state = {}, action) => {
    switch (action.type) {
        case 'RESOLVED_GET_PROFILE':
            return action.data;
        default:
            return state;
    }
};

export default profileReducer;

动作

import * as types from './actionTypes';
import Api from '../middleware/Api';

export function getProfile() {
    return dispatch => {
        dispatch(setLoadingProfileState()); // Show a loading spinner
        Api.getAll('profile').then(profile => {
            dispatch(doneFetchingProfile(profile));
        }).catch(error => {
            throw(error);
        });
        /*Api.fetch(`profile`, (response) => {
            console.log(response)
            dispatch(doneFetchingBook()); // Hide loading spinner
            if(response.status == 200){
                dispatch(setProfile(response.json)); // Use a normal function to set the received state
            }else {
                dispatch(error)
            }
        }) */
    }
}

function setProfile(data) {
    return {type: types.SET_PROFILE, data: data}
    //return { type: types.SET_PROFILE, data: data };
}


function setLoadingProfileState() {
    return {type: types.SHOW_SPINNER}
}

function doneFetchingProfile(data) {
    console.log(data)
    return {
        type: types.HIDE_SPINNER,
        profile: data
    }
}

function error() {
    return {type: types.SHOW_ERROR}
}

但我不知道如何在 getProfile 操作后调度操作并更新状态

【问题讨论】:

    标签: reactjs react-redux dispatch redux-thunk


    【解决方案1】:

    您只需要在调度doneFetchingProfile 之后立即调度您的事件RESOLVED_GET_PROFILE,或者只需收听RESOLVED_GET_PROFILE 并隐藏微调器以减少它。

     Api.getAll('profile').then(profile => {
        dispatch(doneFetchingProfile(profile));
        dispatch(resoloveGetProfile(profile));
     })
    

    实际上你做的一切都是正确的 - 所以我不明白你的问题是什么,所以如果你的意思是别的 - 请告诉我,我会尽力描述你。

    关于调度(resoloveGetProfile(profile));

    你在那里调度动作,它会更新你的状态,就像你对一些静态状态做的那样简单,我看到你已经有setProfile 动作,所以你可以改变那行,调用你现有的函数。

    dispatch(setProfile(profile))
    

    比你需要在这个动作中减少你的状态

    case 'SET_PROFILE' : (action, state) => {...state, profile: action.data}
    

    你的状态会改变,你的组件也会更新。请注意,最好从componentDidMount 调用您的“获取配置文件方法”,以避免由于执行 Web 请求而在渲染时冻结。

    【讨论】:

    • 感谢您的反馈!你能解释一下这部分吗dispatch(resoloveGetProfile(profile));。我要创建一个新函数吗?我在那里做什么?
    • 更新您的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2022-08-17
    • 2016-09-21
    • 2019-08-15
    • 2016-08-21
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多