react-redux与redux-thunk结合使用

React 2020-12-01 1415

react-redux可以更方便的在react中使用redux,而redux-thunk则使逻辑和UI分离,抽离异步代码,单独存放到action文件中,原理就是此中间件可以返回函数。

使用react-redux和redux需要配置,配置的结构比较固定,主要是关注数据的流向。这非常的绕!

数据流向分析:

1.在页面加载过程中,会首先执行mapStateToProps和mapDispatchToProps,获取state的数据。

2.渲染时,父组件中的子组件中,按顺序依此执行,其组件的数据会优先获取

3.父组件的组件执行到componentDidMount生命周期,会查找异步代码,先到当前组件的mapDispatchToProps,查找。

4.由于dispatch(getTopicList());,参数为action,会前往actioncreater.js查找action,异步代码执行,又执行dispatch,接着进入reducer.js,更新state,返回state给组件。

配置:

import {Provider} from 'react-redux'
import store from './store'
import Header from './common/header'

function App() {
  return (// react-redux Provider和store做了关联,内部的组件都有能力获取store数据
    <Provider store={store}>
      <div className="App">
        <Header/>
      </div>
    </Provider>
  );
}

export default App;

header组件

import {connect} from 'react-redux'


class Header extends Component{
  componentDidMount() { // 组件加载完成时
    this.props.getTopicList()
  }
}


const mapStateToProps = (state) => {
  return {
     topicList: state.getIn(['home', 'topicList'])
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getTopicList() {
      console.log('1111111111')
      dispatch(getTopicList());
    }
  }
}
// Header和store作连接
export default connect(mapStateToProps, mapDispatchToProps)(Header);

store/index.js

import reducers from './reducers'
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose; // redux调试工具

const enhancer = composeEnhancers(
  applyMiddleware(thunk) // 添加thunk中间件
);

const store = createStore(
  reducers,
  enhancer
);

export default store;

actionCreater.js

import axios from 'axios'
import {HOME_DATA} from './actionTypes'

const homeData = (res) => ({
  type: HOME_DATA,
  topicList: res.topicList
})

export const getTopicList = () => {
  return (dispatch) => {
    axios.get('http://127.0.0.1:5000/home').then(res => {
      const data = res.data;
      console.log('222222222')
      dispatch(homeData(data));
    })
  }
}

reducer.js

import {fromJS} from 'immutable'
import {HOME_DATA} from './actionTypes'

const defaultState = fromJS({
  topicList: []
})


const changeHomeData = (state, action) => {
  return state.merge({
    topicList: fromJS(action.topicList)
  });
};

export const reducer = (state=defaultState, action) => {
  switch (action.type){
    case HOME_DATA:
      console.log('33333333')
      return changeHomeData(state, action)// 返回新state
    default:
      return state;
  }
}

 

标签:React

文章评论

评论列表

已有0条评论