Redux 中发送异步请求获取数据

1.首先在TodoList中写一个componentDidMount的生命周期函数
2.导入axios包
import axios from 'axios';
3.在componentDidMount的生命周期函数中写出异步获取数据的函数体
    componentDidMount() {
        axios.get('http://yapi.demo.qunar.com/mock/38353/app')
        .then((res) =>{
             alert(suscc);
            
            })
        .catch(alert(err));
    }
4.接下来我们要改变store中的List的数据就必须定义action
5.我们在actionCreators中定义一个action,这个action要返回一个data的数据
import { CHANGE_INPUT_VALUE , ADD_TODO_ITEM , DELET_TODO_ITEM , INIT_LIST_ACTION } from './ActionTypes';
export const initListAction = (data) => ({
    type : INIT_LIST_ACTION,
    data
})

6.然后我们再ActioTypes中定义 INIT_LIST_ACTION这个常量
export const INIT_LIST_ACTION = 'init_list_action';
7.返回TodoList中写异步请求数据函数
    componentDidMount() {
        axios.get('http://yapi.demo.qunar.com/mock/38353/app')
        .then((res) =>{
            const data = res.data;
            const action = initListAction(data)
            store.dispatch(action);
            
            })
        .catch(alert(err));
    }

8.接下来在reducer来处理这个action
    if(action.type === INIT_LIST_ACTION) {
        const newState = JSON.parse(JSON.stringify(state));
        newState.List = action.data;
        return newState; 
    }
9.这样store中的List数据就请求成功了

你可能感兴趣的:(Redux 中发送异步请求获取数据)