redux和axios的结合使用

用途: 用来请求数据

  1. 安装axios
npm install axios
  1. 安装react和redux
npm install react redux

3, 在组件的生命周期componentDidMount中调用接口

 axios.get('http://localhost:3005/api/list').then(res => {
    
    
      let data = res.data
      const action = getListAction(dataList,data)
      store.dispatch(action)
    })

注意: 请求接口存在跨域: 需要解决配置跨域的,
配置的方式在之前的博客提出
博客地址请点击预览

在组件中的使用:

import {
    
    
  dataList
} from '../../store/actionType'
import {
    
    
  getListAction
} from '../../store/actionCreatore'
 componentDidMount () {
    
    
    store.subscribe(this.storechange)
    axios.get('/api/list').then(res => {
    
    
      let data = res.data
      const action = getListAction(dataList,data)
      store.dispatch(action)
    })
  }

在reducer 中的使用

// 创建reducer
const defaultState = {
    
    
  inputValue: '请输入value',
  data: [],
  count: 0
}
xport default (state = defaultState, action) => {
    
    
  console.log(state, action)
  const newState = JSON.parse(JSON.stringify(state))
  switch(action.type) {
    
    
    case dataList:
      newState.data = action.data
      return newState
    default:
      return state
  }
}

store中的写法

// 新建一个仓库
import {
    
     createStore, applyMiddleware, compose } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'
//  增强函数
const componseEnhancers = window._REDUX_DEVTOOLS_EXTENSION_COMPOSE_?
  window._REDUX_DEVTOOLS_EXTENSION_COMPOSE_({
    
    }):compose

const enhancer = componseEnhancers(applyMiddleware(thunk))
// store是唯一的,多个store是不被允许的
// 只有store可以改变自己的内容, reducer是不能改变的
//  reducer是一个纯函数
const store = createStore(
  reducer,
  // applyMiddleware(thunk)
  enhancer
)
// 导出仓库
export default store

猜你喜欢

转载自blog.csdn.net/weixin_45664217/article/details/123157416
今日推荐