react-router 简单封装实践
发布于 7 年前 作者 helloyou2012 4579 次浏览 来自 分享

前面我们已经介绍了一个接口类似 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 。

screenshot.png

回到顶部