【一起来学React】- Reudx学习(二)

版权声明:本文为原创文章,转载请注明出处! https://blog.csdn.net/Fakin/article/details/86077919

上篇文章我们说到redux一些基础和在react中如何运用。本文讲解在react中如何更加优雅的编写redux!
上一篇文章地址:https://blog.csdn.net/Fakin/article/details/85287116

异步Action

在redux中异步的Action只能依靠中间件,没有中间件Redux存储只支持同步数据流。

  • redux-promise或redux-promise-middleware来派遣Promises
  • redux-observable来调度Observable
  • redux-saga
  • redux-pack
  • redux-thunk

这些中介可以让你使用异步的Action,这里咱们主要介绍redux-thunk(因为redux-thunk比较常用,而且易上手)

Middleware

说到redux-thunk,必须得说下Middleware,
它提供的是位于 action 被发起之后,到达 reducer 之前的扩展点。 你可以利用 Redux middleware 来进行日志记录、创建崩溃报告、调用异步接口或者路由等等

import  {createStore, applyMiddleware} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk'
const store = createStore(reducer,
    applyMiddleware(thunk)
);

export default store

上面是一个简单,applyMiddleware是redux帮我们实现的Middleware方法,有了这个方法就可以更加简单些。

redux-thunk

来自redux官方,能够帮助我们发送异步的Action

github

安装:

npm install redux-thunk

示例:

import {GET_BANNER_ACTION} from './actionTypes'
import axios from 'axios'
export const getBanner = () => {
    return (dispatch) => {
        axios.get('/api/banner.json').then(res => {
            if (res.data.message === 'ok') {
                const action = {
                    type: GET_BANNER_ACTION,
                    data: res.data.list
                };
                dispatch(action)
            }
        })
    }
};

//然后在组件中利用react-redux
const mapStateToProps = (state) => {
    return {
        banner: state.home.banner,
    }
};
const mapDispatchToProps = (dispatch) => {
    return {
        getBannerList(){
            dispatch(actionCreatros.getBanner())
        }
    }

}
export default connect(mapStateToProps, mapDispatchToProps)(Home);

//在需要的地方调用
componentDidMount() {
    this.props.getBannerList();
}

更加优雅的Reducer

上一篇文章中我们介绍过Reducer,本文来说说combineReducers.

具体介绍可以查看官网https://redux.js.org/api/combinereducers,
这里我们就介绍下它的用法。

import {combineReducers} from 'redux'
import {reducer as homeReducer} from '../page/home/store'
import {reducer as detailReducer} from '../page/detail/store'
import {reducer as searchReducer} from '../page/search/store/index'
const reducer = combineReducers({
    home: homeReducer,
    detail: detailReducer,
    search: searchReducer
});
export default reducer

这么做的目的是为了更好的区分不同的reducers,然后我们的代码更加的优雅和容易维护!

与React-Router

redux配合React-Router使用,也是非常关键的。

import {Provider} from 'react-redux';
import store from './store'

const Root = ({ store }) => (
  <Provider store={store}>
    <Router>
      <Route path="/" component={App} />
    </Router>
  </Provider>
)

export default Root

ps:很多人都喜欢把所有的state全部交给redux管理,这一点我不是这样的,我把需要共享的数据交给redux,其他的还是交给组件内的state

猜你喜欢

转载自blog.csdn.net/Fakin/article/details/86077919