react-redux异步加载时使用的中间件

1、使用react-redux的thunk中间件
代码:

import { FETCH_START, FETCH_SUCCESS,FETCH_FAILURE} from './actionType'
//使用thunk异步加载
export const fetchWeatherStart = () => {console.log("1")
    return {
        type:FETCH_START
    }
};
export const fetchWeatherSuccess = (result) => {console.log(result)
    return{
        type:FETCH_SUCCESS,
        result
    }
}
export const fetchWeatherFailure = (error) => {console.log("3")
    return{
        type:FETCH_FAILURE,
        error
    }
}
//已经请求到数据了,还没法异步
//这个是thunk中间件的写法,但是出错
//responseJson是一个返回值的参数,里面包含服务器返回给我们的数组名weatheinfo
export const fetchWeather = (cityCode) => {
    return (dispatch) => {
        const apiUrl = `/data/cityinfo/${cityCode}.html`;
        console.log(dispatch)
        dispatch(fetchWeatherStart());//是通过dispatch来派发action
        // dispatch({type:FETCH_START})
// 所以就是在这里是
          fetch(apiUrl).then((response) => {
            if (response.status !== 200) {
                throw new Error('Fail to get response with status ' + response.status);
            }
            response.json().then((responseJson) =>
                dispatch(fetchWeatherSuccess(responseJson.weatherinfo))
                // dispatch({type: FETCH_SUCCESS,result:responseJson.weatherinfo})
            )
            }).catch((error)=>{
              dispatch(fetchWeatherFailure(error))
              // dispatch({type:FETCH_FAILURE,result:error})
          })
}}

2、使用promise的中间件
代码:

//这是promise中间件的写法,只要在store中把thunk改成promise就可以了
export const fetchWeather=(cityCode,dispatch)=> new Promise(function (resolve,reject) {
    const apiUrl = `/data/cityinfo/${cityCode}.html`;
    dispatch(fetchWeatherStart())
    return fetch(apiUrl).then(response=>{
        type:FETCH_FAILURE
    })
})
    export const fetchWeather=(cityCode)=> {
        const apiUrl = `/data/cityinfo/${cityCode}.html`;
        return{
            promise: fetch(apiUrl,{
                method: 'GET',
                    credentials: 'same-origin',
                    headers: {
                    'Content-Type': 'application/json'
                }
            }),
            types: [FETCH_START, FETCH_SUCCESS, FETCH_FAILURE]
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值