React Router v4 / Mobx 出现问题

Having Problems with React Router v4 / Mobx

当我点击我的按钮时,我的路由无法正常工作,但没有任何反应。我正在使用 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>
        )
    }
}

这是因为 @observer 正在优化 shouldComponentUpdate,并阻止您的组件更新。你可以用 withRouter 高阶组件包裹一个组件,它会被赋予当前位置作为它的属性之一,所以 Route 会知道位置改变了。

您可以在这里阅读更多内容:React Router Docs

如果是 PlannerComponent,请尝试将 routingStore 注入包含 Router 组件的组件中,如下所示:

@inject("routingStore")
@observer
class AppContainer extends Component {
  render() {
    return (
      <Router history={history}>
        <PlannerComponent />
      </Router>
    );
  }
}

然后:

ReactDOM.render(
    <Provider {...stores}>
        <AppContainer/>
    </Provider>,
    document.getElementById('root')
);