我想在我的顶级React组件'App'上使用withRouter。

文档在这里:https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md#withrouter-hoc-higher-order-component

我这样使用它:

import React from "react";
import { render } from "react-dom";
import {Router, Link, hashHistory, Route, IndexRoute, withRouter} from "react-router";
import VoteView from "./voteview/Voteview.jsx";
import OverView from "./overview/Overview.jsx";
import AppBar from 'material-ui/AppBar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';

//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

const App = React.createClass({
  render() {
      return (
          <div>
              <AppBar
                title="Democratizer"
                onTitleTouchTap={()=>this.props.router.push('/')}
              >
              </AppBar>
              <br/>

            {this.props.children}
          </div>
      );
  }
});

render((
  <MuiThemeProvider muiTheme={getMuiTheme()}>
    <Router history={hashHistory}>
      <Route path="/" component={App}>
          <Route path="voteview/:baselineId" component={VoteView}/>
          <IndexRoute component={OverView}/>
      </Route>
    </Router>
  </MuiThemeProvider>
  ), document.getElementById('app'));

module.exports = withRouter(App);


我想使用withRouter(App)来使Appbar标题可点击。如果用户单击它,则应打开默认的“/”路径。这就是我尝试使用onTitleTouchTap={()=>this.props.router.push('/')}实现的目标。

我的问题是路由器不存在。用户单击应用栏中的标题时,将触发错误:Uncaught TypeError: Cannot read property 'push' of undefined

withRouter(SomeComponent)对于在组件树下端的组件来说对我来说效果很好。但是在这种情况下,我无法运行它。

有任何想法我做错了吗?

最佳答案

之所以发生这种情况,是因为您在渲染react应用后注入(inject)了路由器。

const App = React.createClass({
  render() {
      return (
          <div>
              <AppBar
                title="Democratizer"
                onTitleTouchTap={()=>this.props.router.push('/')}
              >
              </AppBar>
              <br/>

            {this.props.children}
          </div>
      );
  }
});

App = withRouter(App);


render((
  <MuiThemeProvider muiTheme={getMuiTheme()}>
    <Router history={hashHistory}>
      <Route path="/" component={App}>
          <Route path="voteview/:baselineId" component={VoteView}/>
          <IndexRoute component={OverView}/>
      </Route>
    </Router>
  </MuiThemeProvider>
  ), document.getElementById('app'));

更好的解决方案是像为其他组件所做的那样为App创建文件。
const App = React.createClass({
  render() {
      return (
          <div>
              <AppBar
                title="Democratizer"
                onTitleTouchTap={()=>this.props.router.push('/')}
              >
              </AppBar>
              <br/>

            {this.props.children}
          </div>
      );
  }
});

module.exports = withRouter(App);

并将其导入到index.js中。

10-04 21:41