未捕获(在承诺中)错误:React.Children.only预计会收到一个React元素子元素

时间:2017-04-11 06:32:19

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

我是React JS的新手,试图实现路由到我的新闻应用。我一直在收到以下错误(我正在使用React Router v4 https://reacttraining.com/react-router

Uncaught (in promise) Error: React.Children.only expected to receive a single React element child.
    at invariant (invariant.js:44)
    at Object.onlyChild [as only] (onlyChild.js:33)
    at Router.render (Router.js:99)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)

这是我的路线档案

import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import App from './App.js';
import SourceNews from './SourceNews';


const Routes = () => (

    <Router>
        <div>
            <Route path="/" component={App} />
            <Route path="/news/source/:id" component={SourceNews} />
        </div>
    </Router>
);


export default Routes;

我尝试了这个反应路由器verison 4教程,但似乎没有任何工作

https://reacttraining.com/react-router/web/example/url-params

由于

App.js

import React, { Component } from 'react';
import './App.css';
import './Routes.js';
import NewsList  from './NewsList';
import Header from './Header';

class App extends Component {

    constructor(props) {
       super(props);
       this.state = { sources: [] };
    }

    componentDidMount() {
        fetch('https://newsapi.org/v1/sources?language=en&apiKey=c0f3800ecd5e42f5b1f5bc0e2902bddb')
            .then(result=> result.json())
            .then(json =>  {
                this.setState({sources: json.sources});
            });
    }

    render() {

        const sources = this.state.sources;
        // console.log(sources)
        return (

            <div>
                <Header />
                <NewsList sources={sources} />
            </div>
        )

    }

}

export default App;

更新

参考此文章https://www.sigient.com/blog/movie-listings-application-with-react-router-v-4

解决了这个问题

2 个答案:

答案 0 :(得分:0)

如何更改路线的顺序?

<div>
 <Route path="/news/source/:id" component={SourceNews} />
 <Route path="/" component={App} />
</div>

答案 1 :(得分:0)

确保将您的路线包裹在&#39; Routes.js&#39;文件。然而, 我个人认为你需要更新你的react-router版本,因为你使用旧版本的反应路由器,我建议你使用react-router 4,因为它工作得很好而且不那么混乱。更新react路由器后,您可以按如下方式更新代码:

import { BrowserRouter, Match, Miss } from 'react-router';
...
...
const Routes = () => {
    <BrowserRouter>
        <div>
            <Match exactly pattern="/" component={App} />
            <Match pattern="/news/source/:id" component={SourceNews} />
        </div>
    </BrowserRouter>
}