为什么material-ui在Router内部不起作用(来自react-router)

时间:2017-04-25 11:54:58

标签: react-router material-ui

我尝试使用material-ui和react-router。 这个例子效果很好:

import { Router, Route, IndexRoute, browserHistory } from 'react-router';    
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';


render((
  <div>

    **<MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>**
      <Router history={browserHistory}>
        <Route path="/" component={Authenticated}>
          <IndexRoute component={Home} />
          <Route path="/home" component={Home} />
        </Route>
        {accountRoutes()}
      </Router>
    **</MuiThemeProvider>**
  </div>
), document.getElementById('root'));

请注意,MuiThemeProvider正在包装所有其他组件。

然后我尝试了MuiThemeProvider移动到Router内部。像那样:

render((
  <div>
    <Router history={browserHistory}>
      **<MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>**
        <Route path="/" component={Authenticated}>
          <IndexRoute component={Home} />
          <Route path="/home" component={Home} />
        </Route>
        {accountRoutes()}
      **</MuiThemeProvider>**
    </Router>
  </div>
), document.getElementById('root'));

我有错误

warning.js:36 Warning: Failed context type: The context `muiTheme` is marked as required in `Paper`, but its value is `undefined`.
in Paper (created by Accounts)
in div (created by Accounts)
in div (created by Flexbox)
in Flexbox (created by Accounts)
in Accounts (created by Authenticated)
in Authenticated (created by RouterContext)
in RouterContext (created by Router)
in Router
in div

Uncaught TypeError: Cannot read property 'prepareStyles' of undefined
at Paper.render (Paper.js:96)
at ReactCompositeComponent.js:796
at measureLifeCyclePerf (ReactCompositeComponent.js:75)
at ...

我做错了什么?

1 个答案:

答案 0 :(得分:0)

这是问题和解决方法。路由器组件想要看到他内部的路由。我决定更改我的代码,错误消失了。

const AuthenticatedMui = () => {
  return (
    <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
      <Authenticated />
    </MuiThemeProvider>
  );
};

render((
  <div>
<Router history={browserHistory}>
        <Route path="/" component={AuthenticatedMui }>
          <IndexRoute component={Home} />
          <Route path="/home" component={Home} />
        </Route>
        {accountRoutes()}
      </Router>
    </div>
), document.getElementById('root'));

我创建了AuthenticatedMui并使用它代替Authenticated组件。