IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    react-router 简单封装实践

    helloyou2012发表于 2017-06-02 10:21:01
    love 0

    前面我们已经介绍了一个接口类似 vuex 底层基于 redux 的状态管理库 yax,为了方便结合 react-router 使用我们又造了一个小轮子(插件) yax-router。虽然叫 yax-router 但是就是一个简单的 redux 的 enhancer,所以理论上可以不结合 yax 来用。

    先来一个简单的 Demo

    import React from 'react';
    import ReactDOM from 'react-dom';
    import yax from 'yax';
    import { Provider } from 'react-redux';
    import { Route } from 'react-router';
    import router, { Router, push } from 'yax-router';
    import createHistory from 'history/createBrowserHistory';
    
    const history = createHistory();
    const store = yax({
      state: {},
      reducers: {},
      actions: {},
      modules: {}
    }, router(history));
    
    store
      .onRoute('/', ({ match, location, dispatch }) => {});
      .onRoute('/topics', ({ match, location, dispatch }) => {});
      .onRoute('/topic/:id', ({ match, location, dispatch }) => {});
    
    const Home = () => <div>Home</div>;
    const Topic = ({ match }) => <div>Topic{match.params.id}</div>;
    const Topics = () => <div>Topics</div>;
    
    // store.dispatch(push('/'));
    
    ReactDOM.render(
      <Provider store={store}>
        <Router history={history}>
          <div>
            <ul>
              <li><Link to="/">Home</Link></li>
              <li><Link to="/topic/1">Topic</Link></li>
              <li><Link to="/topics">Topics</Link></li>
            </ul>
            <hr/>
            <Route exact path="/" component={Home}/>
            <Route path="/topic/:id" component={Topic}/>
            <Route path="/topics" component={Topics}/>
          </div>
        </Router>
      </Provider>,
      document.getElementById('root')
    );
    

    是不是用起来很简单清新脱俗~~~

    再来看一下接口

    import router from 'yax-router';
    
    type router = (history) => Enhancer
    

    然后呢,没有了。。。就一个接口。。。。慢着好像还漏了点

    type onRoute = (path: String, handler: Handler, exact: Boolean) => any
    
    type Handler = ({ location, match, dispatch }) => any
    
    type offRoute = (path: String) => any
    

    最后再来个复杂点的 Demo

    这个例子由 dva-hackernews 修改而来,只不过把 dva 改成了 yax 。

    • Github 地址:https://github.com/d-band/yax-hackernews
    • Demo 地址:https://yax-hn.now.sh

    screenshot.png



沪ICP备19023445号-2号
友情链接