无法正确设置React-Router-Dom

时间:2017-06-15 01:28:44

标签: javascript reactjs react-router-v4

您好,我目前正与react-router-dom合作。我似乎没有正确地遵循指示,因为我遇到了这个问题:

bundle.js:1085 Warning: Failed prop type: The prop `history` is marked as required in `Router`, but its value is `undefined`.
  in Router

bundle.js:2279 Uncaught Error: A <Router> may have only one child element
    at invariant (bundle.js:2279)
    at Router.componentWillMount (bundle.js:47987)
    at bundle.js:35732
    at measureLifeCyclePerf (bundle.js:35459)
    at ReactCompositeComponentWrapper.performInitialMount (bundle.js:35731)
    at ReactCompositeComponentWrapper.mountComponent (bundle.js:35642)
    at Object.mountComponent (bundle.js:41991)
    at ReactCompositeComponentWrapper.performInitialMount (bundle.js:35755)
    at ReactCompositeComponentWrapper.mountComponent (bundle.js:35642)
    at Object.mountComponent (bundle.js:41991)

这些是我使用react-router-dom的应用程序的一部分:

routes.js:

"use strict";
const React = require('react');
const Switch = require('react-router-dom').Switch;
const Route = require('react-router-dom').Route;
const Router = require('react-router-dom').Router;
const Home = require('./components/homepage');
const AuthorPage = require('./components/authors/authorPage');
const About = require('./components/about/aboutpage');

const Routes = (
    <Router>
        <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/authors" component={AuthorPage} />
            <Route path="/about" component={About} />
        </Switch>
    </Router>
);

module.exports = Routes;

main.js:

"use strict";
const React = require('react');
const ReactDOM = require('react-dom');
const BrowserRouter = require('react-router-dom').BrowserRouter;
const App = require('./components/app');

ReactDOM.render(<BrowserRouter> <App /> </BrowserRouter>, document.getElementById('app'));

app.js:

$ = jQuery = require('jquery');
const React = require('react');
const Header = require('./common/header');
const Routes = require('../routes');

class App extends React.Component {
    render() {
        return (
            <div>
                <Header />
                <Routes />
            </div>  
        );
    }
}

module.exports = App;

更新1:

我删除了 routes.js 中的<Router> </Router>包装,第一个错误消失了。感谢:@Keith Alpichi

1 个答案:

答案 0 :(得分:1)

首先,Router requires a history object。导入createBrowserHistory然后创建它。

import createBrowserHistory from 'history/createBrowserHistory'

const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>

但是,您必须决定是否要使用BrowserRouter或普通Router,因为仅基于文档Router需要history对象。如果您决定使用前者,请从Router中声明的Routes变量中移除routes.js。如果您决定使用Router BrowserRouter main.js更改Router。{/ p>

其次,由于您已经在main.js中定义了Router组件,因此您不需要routes.js中的另一个组件。因此,请删除外部Router标记,如下所示:

const Routes = (
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/authors" component={AuthorPage} />
    <Route path="/about" component={About} />
  </Switch>
);