在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5  HTML/ 關(guān)于react 異步action的疑問

關(guān)于react 異步action的疑問

下面是沒有使用異步action的代碼

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        onLoadSuccessHandle: (weather) => {
            dispatch(loadSuccess(weather))
        },
        onLoadFailureHandle: () => {
            dispatch(loadFailure())
        }
    }
}


    componentDidMount() {
        const cityCode = 101010100

        const apiUrl = `/data/cityinfo/${cityCode}.html`;

        fetch(apiUrl).then((response) => {
            if (response.status !== 200) {
                throw new Error('Fail to get response with status ' + response.status);
            }
    
            response.json().then((responseJson) => {
                this.props.onLoadSuccessHandle(responseJson.weatherinfo)
            }).catch((error) => {
                this.props.onLoadFailureHandle()
            });
        }).catch((error) => {
            this.props.onLoadFailureHandle()
        });
    }

這里是一個異步action

export const loadWeather = () => {
    return (dispatch) => {
        dispatch(loadStarted())

        const cityCode = 101010100
        const apiUrl   = `/data/cityinfo/${cityCode}.html`
        fetch(apiUrl).then((response) => {
            if (response.status !== 200) {
                throw new Error('Fail to get response with status ' + response.status);
            }
    
            response.json().then((responseJson) => {
                dispatch(loadSuccess(responseJson.weatherinfo))
            }).catch((error) => {
                dispatch(loadFailure())
            });
        }).catch((error) => {
            dispatch(loadFailure())
        });


    }
}

上面的異步action方式,把發(fā)起請求這一環(huán)節(jié)的代碼封裝到了action里面,也就是說異步action只是為了統(tǒng)一dispatch的接口?

回答
編輯回答
枕頭人

這樣可以讓你的組件更干凈,把這種url請求和表現(xiàn)分開,利于復(fù)用以及單元測試

2018年1月23日 07:19