react服务端渲染(七)redux添加

  1. 使用,添加一个redux-thunk中间件,支持异步action操作
    import { Provider } from 'react-redux';
    import { createStore, applyMiddleware } from 'redux';
    import thunk from 'redux-thunk';
    
    import Router from '../router'
    import Rducer from '../reducer'
    
    const Store = createStore(Rducer, applyMiddleware(thunk));
    
    const App = () => {
        return(
            <Provider store={Store}>
                <BrowserRouter>
                    <Router/>
                </BrowserRouter>
            </Provider>
        )
    }
  2. 默认情况下redux只能dispatch一个plain object,例如:

    dispatch({
        type: 'SOME_ACTION_TYPE',
        data: 'xxxx'
    });

    使用 redux-thunk 之后,可以dispatch一个函数了,这个函数会接收dispatch, getState作为参数,在这个函数里你就可以干你想干的事情,在任何地方随意dispatch了,例如下面这个ajax请求:

    dispatch(function (dispatch) {
        $.get('/api/users', function(users) {
            dispatch({
                type: 'FETCH_USERS_SUCCESS',
                users: users,
            });
        });
    });
  3. 这时候有一个疑问,redux-thunk的作用是什么?为什么不用异步dispatch(action)来调用?
    //thunk
    export const test = () => {
        return dispatch => {
            setTimeout(()=>{
                dispatch({type: "change"})
            },1000)
        }
    }
    //异步dispatch
    export const test2 = (dispatch)=> {
        setTimeout(()=>{
            dispatch({type: "change"})
        },1000)
    }

    这二者有什么区别?

  4. 这两种写法对组件来说是没有任何区别的。我们需要注意的是redux-thunk是一个中间件,作用是对redux进行功能的增强,也就是在redux的流程中进行一些其他的处理,redux的流程:action-> dispatcher -> reducer -> store tree changed -> relative components re-render -> UI changed;我们使用thunk是在dispatch action以及action 到达action之间进行一些其他的操作。而我们直接使用异步dipatch并没有增强我们redux的功能!(暂时想到的区别就只有这个)

 项目地址:git@github.com:longlongdan/Reactssr.git

posted @ 2019-08-01 17:06  祖国的小花朵  阅读(289)  评论(0编辑  收藏  举报