使用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
应用活动类。
答案 0 :(得分:4)
我只需要堆叠我的类包装器/装饰器。 这个例子使用了基础createReactApp,因此没有装饰器,但我使用的实际用例是使用createReactApp的typescript fork并支持装饰器。
我的问题是通过在类上堆叠装饰器来解决的,以便反应路由器和mobx的context
被传递下来。
示例:
@withRouter
@inject('store')
@observer
export class MyComponent extends React.Component{
...
}