当我点击我的按钮没有任何反应时,我无法让我的路由工作。我正在使用mobx-react-router
import plannerStore from './PlannerStore';
import { RouterStore } from 'mobx-react-router';
const routingStore = new RouterStore();
const stores = {
plannerStore,
routingStore
}
export default stores;
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'mobx-react';
import { useStrict } from 'mobx';
import createBrowserHistory from 'history/createBrowserHistory';
import { syncHistoryWithStore } from 'mobx-react-router';
import { Router } from 'react-router';
import App from './App';
import PlannerComponent from './components/PlannerComponent';
const browserHistory = createBrowserHistory();
import stores from './stores/index';
const history = syncHistoryWithStore(browserHistory, stores.routingStore);
useStrict(true);
ReactDOM.render(
<Provider {...stores}>
<Router history={history}>
<PlannerComponent />
</Router>
</Provider>,
document.getElementById('root')
);
import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {observer, inject} from 'mobx-react';
import CourseComponent from './CourseComponent';
import GradeComponent from './GradeComponent'
import { Route } from 'react-router';
@inject('plannerStore', 'routingStore')
@observer
export default class PlannerComponent extends Component {
constructor() {
super();
}
render() {
return (
<div>
<CourseComponent />
<Route path='/grade' component={GradeComponent}/>
</div>
)
}
}
import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {observer, inject} from 'mobx-react';
import planner from '../styles/planner.scss'
@inject('plannerStore', 'routingStore')
@observer
export default class CourseComponent extends Component {
constructor() {
super();
}
render() {
const { location, push, goBack } = this.props.routingStore;
return (
<div >
<button onClick={() => push('/grade')}>grades</button>
</div>
)
}
}
答案 0 :(得分:3)
这是因为@observer
正在优化shouldComponentUpdate
,并阻止您的组件更新。您可以使用withRouter
高阶组件包装组件,并将其当前位置作为其道具之一,因此Route
将知道位置已更改。
您可以在此处阅读更多内容:React Router Docs
答案 1 :(得分:0)
尝试在包含Router组件的组件中注入routingStore,如果是PlannerComponent,则如下所示:
@inject("routingStore")
@observer
class AppContainer extends Component {
render() {
return (
<Router history={history}>
<PlannerComponent />
</Router>
);
}
}
然后:
ReactDOM.render(
<Provider {...stores}>
<AppContainer/>
</Provider>,
document.getElementById('root')
);