为什么mobx-react观察者会破坏react-router-dom navlink活动类?

时间:2017-04-27 15:07:53

标签: reactjs react-router mobx mobx-react react-router-dom

使用react-router的{​​{1}}时,NavLink的{​​{1}}组件上的活动类的应用已损坏。

产生问题的设置:

使用create react app

的package.json

{
  "name": "routertest",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "mobx": "^3.1.9",
    "mobx-react": "^4.1.8",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^4.1.1"
  },
  "devDependencies": {
    "react-scripts": "0.9.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

App.js

import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom'
import Nav from './Nav';
import './App.css';

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)

const About = () => (
  <div>
    <h2>About</h2>
  </div>
)
const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
  </div>
)



class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div className="App">
          <Nav />
          <hr />
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/topics" component={Topics} />
        </div>
      </BrowserRouter >
    );
  }
}

export default App;

Nav.js

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import { observer } from 'mobx-react';

const Nav = observer (class Nav extends Component {
    render() {
        return (
            <ul>
                <li><NavLink exact to="/" activeClassName="active">Home</NavLink></li>
                <li><NavLink to="/about" activeClassName="active">About</NavLink></li>
                <li><NavLink to="/topics" activeClassName="active">Topics</NavLink></li>
            </ul>
        );
    }
})

export default Nav;

这是问题的简化显示。我的用例涉及实际使用mobx store创建NavLink并使用装饰器。寻找为什么观察者包装器阻止react-router-dom应用活动类。

1 个答案:

答案 0 :(得分:4)

我只需要堆叠我的类包装器/装饰器。 这个例子使用了基础createReactApp,因此没有装饰器,但我使用的实际用例是使用createReactApp的typescript fork并支持装饰器。

我的问题是通过在类上堆叠装饰器来解决的,以便反应路由器和mobx的context被传递下来。

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

示例:

@withRouter
@inject('store')
@observer
export class MyComponent extends React.Component{
...
}