react:dispatch處理請求到的數據(redux,actoin,reducer)

  1. react定義一個組件,綁定兩個屬性 hisTotalAmount, getTotalAmount
  2. 定義action函數 getTotalAmount
  3. 定義reducer函數 hisTotalAmount
  4. 回到組件在componentWillReceiveProps函數內直接通過hisTotalAmount判斷是否相等,就可以確定數據是否回來,再通過setState重新回載數據
定義組件

src/container/index.js文件

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import {getTotalAmount, } from '../../redux/actions'
class WaitContainer extends Component {
	....省略其它代碼
	  componentWillReceiveProps(nextProps) {
		      if (this.props.hisTotalAmount !== nextProps.hisTotalAmount && nextProps.hisTotalAmount.preload){
				console.log("hisTotalAmount返回結果: ",nextProps.hisTotalAmount)
				  this.setState({
					  total_amount: nextProps.hisTotalAmount.total_amount,

				  })
			  }
	  }
	....省略其它代碼
}
WaitContainer.propTypes = {
  hisTotalAmount:PropTypes.object.isRequired,
}
function mapStateToProps(state) {
  return {
    hisTotalAmount : state.hisTotalAmount,
  }
}
function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({
      getTotalAmount,
    }, dispatch),
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(WaitContainer))
定義action函數

src/redux/actions/total.act.js文件

import * as TYPES from '../types'
export function getTotalAmount(opt) {
    return (dispatch) => {
        const route = 'total_amount'
        const method = 'GET'
        const headers = {
            ...HEADERS,
            Authorization: opt.token,
        }
        const success = (data) => {
            console.log("hisTotalAmount action 返回結果: ",data)
            dispatch({ type: TYPES.TOTAL_AMOUNT, result: data })
        }
        //調用請求數據
        request(route, opt.params, dispatch, success, { method, headers })
    }
}

src/redux/actions/index.js文件

export {
getTotalAmount,

} from './total.act'
定義reducer函數

src/redux/reducers/index.js文件

export {
hisTotalAmount,
} from './total.rdc'

src/redux/reducers/total.rdc.js 文件

import * as TYPES from '../types'
const initialState = {
  preload: false,
  items: [],
}
export function hisTotalAmount(state = initialState, action) {
    console.log("hisTotalAmount reducer 返回結果: ",action)
    switch (action.type) {
        case TYPES.TOTAL_AMOUNT:
            return {
                ...state,
                preload: true,
                ...action.result,
            }
        default:
            return state
    }
}

src/redux/type.js文件

export const TOTAL_AMOUNT = 'TOTAL_AMOUNT'
定義Store
src/redux/configureStore.js文件
import { createStore, combineReducers, compose, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'

import { routerReducer, routerMiddleware } from 'react-router-redux'
import { pendingTasksReducer } from 'react-redux-spinner'

import * as reducers from './reducers'

export default function configureStore(history, initialState) {
  const reducer = combineReducers({
    ...reducers,
    routing: routerReducer,
    pendingTasks: pendingTasksReducer,
  })
  // const loggerMiddleware = createLogger()
  const store = createStore(
    reducer,
    initialState,
    compose(
      applyMiddleware(
        thunkMiddleware,
        routerMiddleware(history),
      ),
    ),
  )
  return store
}
最後是初始化加載store

src/entries/index.js文件

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { Router, hashHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import routes from '../routes/'
import { LocaleProvider } from 'antd';
import zhCN from 'antd/lib/locale-provider/zh_CN';
import configureStore from '../redux/configureStore'
const store = configureStore(hashHistory)
const { document } = global
const history = syncHistoryWithStore(hashHistory, store)
render(
    (
      <Provider store={store}>
        <LocaleProvider locale={zhCN}>
          <Router history={history} routes={routes} />
        </LocaleProvider>
      </Provider>
    ), document.getElementById('root'),
)
通過webpack 加載入口index

{ProjectRoot}/webpack.config.js文件

const path = require('path')
const webpack = require('webpack')
const nodeModulesPath = path.join(__dirname, '/node_modules')
module.exports = {
  entry: {
    index: './src/entries/',
    vendor: ['react', 'react-dom', 'redux', 'antd'],
  },
  ....省略其它代碼
  }

關於webpack還是得去看看詳細的資料
webpack超詳細配置,使用教程(圖文)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章