react:dispatch处理请求到的数据(redux,actoin,reducer)

  1. react定义一个组件,绑定两个属性 hisTotalAmount, getTotalAmount
  2. 定义action函数 getTotalAmount
  3. 定义reducer函数 hisTotalAmount
  4. 回到组件在componentWillReceiveProps函数内直接通过hisTotalAmount判断是否相等,就可以确定数据是否回来,再通过setState重新回载数据
  5. 触发请求后经过action.getTotalAmount 进入reducer.hisTotalAmount 返回到mapStateToProps{state.hisTotalAmount} ,然后componentWillReceiveProps(nextProps.hisTotalAmount) 就可以获取结果,再通过setState进行渲染
react版本:
"react": "^15.4.1",
"react-router": "^3.0.0",
"react-redux": "^4.4.6",
"redux-thunk": "^2.1.0",
"prop-types": "^15.5.9",
定义组件

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,//对应的就是下面文件中total.rdc.js->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超详细配置,使用教程(图文)

深入浅出Redux
深入浅出Redux实现原理

拷贝一部分我觉得能帮助理解的内容
bindActionCreators:
但如果我有很多个Action,总不能手动一个一个加。Redux提供了一个方法叫 bindActionCreators。
bindActionCreators 的作用就是将 Actions 和 dispatch 组合起来生成 mapDispatchToProps 需要生成的内容。
它看起来像这样:


let actions = {
  addItem: (text) => {
    type: types.ADD_ITEM,
    text
  }
}

bindActionCreators(actions, dispatch); // @return {addItem: (text) => dispatch({ type: types.ADD_ITEM, text })}

这是一部分核心源码:

function bindActionCreator(actionCreator, dispatch) {
  return (...args) => dispatch(actionCreator(...args));
}

// mapValues: map第一个参数的每一项,返回对象,key是key,value是第二个参数返回的数据

/*
 * mapValues: map第一个参数的每一项,返回对象,key是key,value是第二个参数返回的数据
 * 
 * @param actionCreators
 * @param dispatch
 *
 * @return {actionKey: (...args) => dispatch(actionCreator(...args))}
 */
export default function bindActionCreators(actionCreators, dispatch) {
  return mapValues(actionCreators, actionCreator =>
    bindActionCreator(actionCreator, dispatch)
  );
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值