用途: 用来请求数据
- 安装axios
npm install axios
- 安装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 中的使用
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))
const store = createStore(
reducer,
enhancer
)
export default store
|