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

2022-03-20  本文已影响0人  泡杯感冒灵
步骤
  1. 首先,引入axios,在生命周期函数componentDidMount中发送请求。
  2. 获取到数据后,通过store.dispatch派发一个action给store,store拿到这个action连同原先的数据,一起发给reducer。
  3. reducer里,深拷贝store传来的数据,然后改变拷贝对象的数据,再把这个拷贝对象返回给store
  4. store拿到这个拷贝对象,替换原来的数据
  5. 组件通过store.subscribe方法订阅了store的变化,这个时候执行传给subscribe的函数,通过setState更新组件的state。
import axios from 'axios';

componentDidMount(){
      axios.get('/list.json').then((res)=>{
            const data = res.data;
            const action = initListAction(data);
            store.dispatch(action);
      })
 }

// actionCreators.js
export  const initListAction = (data) => ({
    type: INIT_LIST_ACTION,
    data
})

//  reducer.js
if(action.type === INIT_LIST_ACTION){
        const newState = JSON.parse(JSON.stringify(state));
        newState.list = action.data;
        return newState;
 }

上一篇 下一篇

猜你喜欢

热点阅读