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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值