LoginSignup
4
5

More than 5 years have passed since last update.

Flumpt + React-Router

Last updated at Posted at 2016-04-27

概要

Flumpt と React Router の組合せ方。

環境

Router

const routes = (
  <Route path="/" component={Root}>
    <IndexRoute component={IndexPage}/>
    <Route path="/mycomponent" component={MyComponentPage}/>
  </Route>
);

class Routes extends React.Component {
  render() {
    return (
      <Router history={browserHistory} routes={routes}/>
    );
  }
}

注意

<Router history={browserHistory}>
  <Route path="/" component={Root}>
    <IndexRoute component={IndexPage}/>
    <Route path="/mycomponent" component={MyComponentPage}/>
  </Route>
</Router>

React Router では上のように書くことができるが、 Warning: [react-router] You cannot change <Router routes>; it will be ignored という警告が表示されるので、回避策として、routesrender() の外で定義する必要がある。

各ページのコンポーネント

  • Flumpt.Component を継承する。
  • this.context.emitter.state からステートを取得する。
import {Component} from 'flumpt';

class MyComponentPage extends Component {
  componentDidMount() {
    this.dispatch("increment");
  }

  render() {
    const {count} = this.context.emitter.state;

    return (
      <div>
        <Link to="/">Home</Link>
        <hr />
        {count}
        <br />
        <button onClick={() => this.dispatch("increment")}>increment</button>
      </div>
    );
  }
}

App

<Routes />を書くだけ。

class App extends Flux {
  subscribe() { // `subscribe` is called once in constructor
    this.on("increment", () => {
      this.update(({count}) => {
        return {count: count + 1}; // return next state
      });
    });
  }

  render(state) {
    return <Routes {...state}/>;
  }
}

サンプルコード

最後に

Reduxに慣れすぎて、context.emitter.state からステートを取るのに違和感があるので、react-reduxconnectのようなものを作りたい。

参考

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5