React.Children.only希望在React Router v4中收到一个React元素子元素

时间:2017-07-09 02:02:31

标签: reactjs debugging react-router react-router-v4 react-router-dom

我安装了react-router-dom 4.1.1并在尝试渲染我的组件时一直收到以下错误:

  

未捕获错误:React.Children.only预计会收到一个React元素子项。

这是我的app.js文件:

import React from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Nav from './components/Nav/nav';
import Search from './components/Search/search';
import Favorites from './components/Favorites/favorites';

const App = () => (
 <Router>
    <div className="app">
      <Nav />
      <Route exact path="/" component={Search}/>
      <Route path="/favorites" component={Favorites}/>
    </div>
  </Router>
);

export default App;

这是nav.jsx

import React from 'react';
import {BrowserRouter as NavLink} from 'react-router-dom';

const Nav = () => (
    <ul className="nav">
        <li><NavLink exact to="/" activeClassname="active">Search</NavLink></li>
        <li><NavLink to="/favorites" activeClassname="active">Favorites</NavLink></li>
    </ul>
);

export default Nav;

当我从<Nav />移除app.js时,我会看到nav.jsx文件有什么问题。

1 个答案:

答案 0 :(得分:8)

由于一些奇怪的原因,您将BrowserRouter别名为NavLink而不是仅导入NavLink

import { BrowserRouter as NavLink } from 'react-router-dom';

摆脱它并直接导入为名称:

import { NavLink } from 'react-router-dom';

因为BrowserRouter需要一个 React元素子元素而不是文本,所以会抛出错误。