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

  • Post author:
  • Post category:其他


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]
        }
    }



版权声明:本文为qq_26983555原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。