操作redux 状态的时候,先会通过中间件拦截,可在这个过程中进行操作

reducer 相当于 vuex中的 state,根据type 返回值 actions 相当于 vuex中的 action, dispatch触发

  • 需要引入 redux 的 applyMiddleware ```javascript import {createStore, applyMiddleware } from ‘redux’

// 中间件 const logger = store => next => action => { console.log(‘dispatch’, action) let result = next(action) // 加载下一个中间件 console.log(‘next state =>’, store.getState()) return result }

const error = store => next => action => { try{ next(action) } catch(e) { console.log(‘error=>’, e) } }

// 注册到store上面 const store = createStore(rootReducer, {}, applyMiddleware(logger,error))

  1. - 第三方中间件
  2. cnpm i -D redux-logger
  3. ```javascript
  4. import logger from 'redux-logger'
  5. const store = createStore(rootReducer, {}, applyMiddleware(logger))

异步操作 , actions中

使用setTimeout模拟异步

  1. export const increment = (num) => {
  2. return dispatch => {
  3. setTimeout(() => {
  4. dispatch({
  5. type: constants.INCREMENT,
  6. num
  7. })
  8. }, 1000)
  9. }
  10. }
  • 需要在index.js中引入 redux-thunk cnpm i -D redux-thunk
  1. import thunk from 'redux-thunk'
  2. // actions 可以使用异步 全局引用一次
  3. const store = createStore(rootReducer, {}, applyMiddleware(logger,thunk))

实例

  • actions/user.js ```javascript import {FETCH_USER} from ‘../constants’

export function fetchUser(user) { return { type: FETCH_USER, user } }

// 异步转同步的网络请求 export const getUser = () => { return dispatch => { fetch(‘https://douban.uieee.com/v2/movie/in_theaters').then(res => res.json()).then(data => { // 修改 state dispatch(fetchUser(data)) }).catch(err => { console.log(err) }) } }

  1. - reducer/user.js
  2. ```javascript
  3. import {FETCH_USER} from '../constants'
  4. // reducer是个纯函数, 改变store数据的
  5. // 数据在action 中
  6. // 改变对象
  7. const initState = {
  8. userInfo: {
  9. title: 1
  10. }
  11. }
  12. // state 只读的,必须返回一个新对象
  13. const counter = (state = initState, action) => { // action对象 actions中的文件
  14. switch(action.type) {
  15. case FETCH_USER:
  16. // 返回新对象
  17. return {
  18. userInfo: action.user
  19. }
  20. default:
  21. return state
  22. }
  23. }
  24. export default counter
  • 页面触发
  1. import React from 'react';
  2. import {connect} from 'react-redux'
  3. import {bindActionCreators} from 'redux'
  4. import * as userActions from '../actions/user'
  5. class User extends React.Component{
  6. render() {
  7. return (
  8. <div className='container' >
  9. <p className='text-center'>我是 user {this.props.name}</p>
  10. <p className='text-center'>userInfo: {this.props.user.userInfo.title}</p>
  11. <button onClick={() => this.props.userActions.getUser()}>获取数据</button>
  12. </div>
  13. )
  14. }
  15. }
  16. const mapStateToProps = (state) => {
  17. console.log(state)
  18. return {
  19. user: state.user
  20. }
  21. }
  22. const mapDispatchToProps = (dispatch) => {
  23. return {
  24. userActions: bindActionCreators(userActions, dispatch)
  25. }
  26. }
  27. export default connect(mapStateToProps, mapDispatchToProps)(User)