React (7) ajax 获取数据

1.  为什么要用中间件

Action 发出以后,Reducer 立即算出 State,这叫做同步;

Action 发出以后,过一段时间再执行 Reducer,这就是异步。

中间件就是让 Reducer 在异步操作结束后自动执行

store/index.js 

1. 引入 redux-thunk

import {createStore,applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk'
import reducer from './reducer';
const composeEnhancers =
  typeof window === 'object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;

const enhancer = composeEnhancers(
    applyMiddleware(thunk),
    // other store enhancers if any
    );
const store = createStore(reducer, enhancer);

export default store;

2.  组件内用户执行动作

const mapDispatchToProps = (dispatch) => {
    return {
        handleFocus() {
            dispatch(actionCreators.getList()); // 异步获取数据
        },
    }
}

3.  dispatch(action)  想要actionCreators返回函数,必须使用redux-thunk

const changeList = (data) => ({
        type:actionTypes.GET_LIST,
        data: fromJS(data) // 这里传过去的数组也要转换成immutable数组
})
   
export const getList = ()=> { // 异步获取数据返回一个函数,而不是一个对象
        return (dispatch) =>{
                axios.get('/api/headerList.json').then((res)=>{
                        // create-react-app 底层是node的服务器
                        // 当你访问接口的时候,它会先到工程目录(src)去看有没有路由
                        // 如果没有找到, 它还会在public公共目录下去找  
                        dispatch(changeList(res.data.data))
                }).catch((e)=>{
                        console.log(e)
                })
        }    
}

4.  模拟数据 (这里可以自己写一些数据,模拟, 等后台有数据再换,事前沟通好数据类型)

为什么可以写在public下面 :

因为create-react-app 底层是node的服务器  , 当你访问接口的时候,它会先到工程目录(src)去看有没有  , 如果没有找到, 它还会在public公共目录下去找.

5.  reducer 结束action处理state

 if (action.type === actionTypes.GET_LIST){
        return state.set('list', action.data);
    }

 6. 组件接收新的list, 然后在页面上使用

const mapStateToProps = (state) => {
    return {
        focused: state.getIn(['header','focused']),
        list: state.getIn(['header','list'])
    }
}

猜你喜欢

转载自blog.csdn.net/jiandan1127/article/details/85052782