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
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
  }
}

店頭での書き方

// 新建一个仓库
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