bai3/note

Subscription和Router

Opened this issue · 0 comments

bai3 commented

Subscription

subscription是订阅,用于订阅一个数据源,然后根据需要dispatch相应的action。数据源可以是当前的时间,服务器websocket连接、keyboard输入、geolocation变化、history路由变化。格式为({dispatch,history}) => unsubscription

异步数据初始化

比如:当用户进入/user页面时,触发action users/fetch加载用户数据

app.model({
    subscriptions: {
        setup({ dispatch, history }){
            history.listen(({pathname}) => {
                if(pathname == '/users'){
                    dispatch({
                        type:'user/fetch'
                    })
                }
            })
        }
    }
})

path-to-regexp Package

如果url规则比较复杂,比如/user/:userId/search,那么匹配和userId的获取都会比较麻烦。这里推荐用path-to-regexp简化这部分逻辑

import { pathToRegexp } from "path-to-regexp";

const match = pathToRegexp('/users/:userId/search').exec(pathname);
if(match) {
    const userId = match[1]
}

Router

Config with JSX Element (router.js)

<Route path="/" component={App}>
	<Route path="accounts" component={Accounts}></Route>
</Route>

Route Components

Route Components是指 ./src/routes/ 目录下的文件,他们是 ./src/router.js里匹配的Component

通过connect绑定数据

比如

import {connect} from 'dva'
function App(){}
function mapStateToProps(state, ownProps) {
    return {
        users: state.users
    }
}
export default connect(mapStateToProps)(App)

然后在App里就有了dispatch 和 users两个属性

基于action进行页面跳转

import { routerRedux } from "dva/router";

yield put(routerRedux.push('/logout'));

dispatch(routerRedux.push('/logout'));

routerRedux.push({
    pathname: '/logout',
    query:{
        page: 2
    }
})