16 react 发送异步请求获取数据 和 使用Redux-thunk中间件进行 ajax 请求发送

1.发送异步请求获取数据

  1.引入 axios ( 使用 yarn add axios 进行安装 )

    import axios from 'axios';

  2. 模拟 在元素完成挂载后加载数据 并初始化 redux

    # TodoList.js

    componentDidMount(){

      axios.get('http://xxx/xxx').then( ( response ) => {

        const data = response.data;

        const action = {

          type: 'init_store_data',

          value: data

        }

        store.dispatch(action);

      })

    }

    # reducer.js

    export default (status, action)=>{

      if( action.type === 'init_store_data' ){

        const newState = JSON.parse(JSON.stringify( status ));

        newState.list = action.value ;

        return newState;

      }

    }

2. 使用Redux-thunk中间件进行 ajax 请求发送

  当 ajax请求很多 的时候 需要把 异步请求分装到其他地方进行管理

  此时就需要 使用 redux-thunk

  1. 安装 redux-thunk

    yarn add redux-thunk

  2.使用 redux-thunk

    创建 store 并使用 applyMiddleware 引入 redux-thunk 方法

    #store/index.js

      import {createStore, applyMiddleware, compose} from 'redux';

      import reducer from './reducer';

      import thunk from 'redux-thunk';

      // 校验 redux devtool 是否存在

      const composeEnhancers =

       window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?

        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;

      // composeEnhancers 引入 thunk 中间件

      const enhancer = composeEnhancers(

       applyMiddleware(thunk)

      );

      // 合并后的中间件 作为 redux 的中间件

      const store = createStore(reducer, enhancer);

      export default store;

    #创建 action 文件夹 并在 action 文件夹下创建 index.js 并写入

      import axios from 'axios';

      export const loadInitData = ()=>{

      return (dispatch)=>{

       axios.get('http://index.com/front/article')

       .then((res)=>{

       const data = res.data.data.map((val)=>val.title);

       const action = {

       type : 'init_data',

       value : data

       }

       dispatch(action);

       })

       }

      }

    # store 下的 reducer.js 添加 类型判断      

      if(action.type === 'init_data'){

      const newState = JSON.parse(JSON.stringify(state))

      newState.list = action.value;

      return newState;

     }

    # TodoList.js 修改 componentDidMount

      import { loadInitData } from './action';

      componentDidMount(){

      const action = loadInitData();

      store.dispatch(action);

      }

    即可异步发送 ajax 请求