React 4 Router error = type是无效的预期字符串但未定义

时间:2017-05-21 03:26:04

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

有一个非常直接的反应问题,我正在尝试做一些直接的路由。主页,个人资料页面,404页。但是继续得到同样的错误。

我的组件似乎正在工作,因为我已成功将它们渲染出来,但是当我尝试实现路由时,我收到以下错误。

错误:Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of Root.

我之前已经有了这样的路由(路由器v 4.0.0反应),所以我不确定我在这里犯了什么错误。任何正确方向的推动都将受到赞赏。提前谢谢。

App.js

import React, { Component } from 'react';
import ReactDOM, { render } from 'react-dom';
import { BrowserRouter as Router, Match, Miss } from 'react-router';

//Components
import Home from './components/Home';
import Profile from './components/Profile';
import NotFound from './components/NotFound';

const Routes = () => {
    return (
        <Router>
            <div>
                <Match exactly pattern="/" component={Home} />
                <Match exactly pattern="/profile/:profileId" component={Profile} />
                <Miss component={NotFound} />
            </div>
        </Router>
    )
}

render(<Routes />, document.querySelector('#container')); 

主页组件

import React, { Component } from 'react';

class Home extends Component {
    render() {
        return (
            <p>Home Page</p>
        )
    }
}

export default Home;

个人资料组件

import React, { Component } from 'react';

class Profile extends Component {
    render() {
        return (
            <p>Profile Page</p>
        )
    }
}

export default Profile;

的package.json

  "dependencies": {
    "html-webpack-plugin": "^2.28.0",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router": "^4.1.1",
    "webpack": "^2.5.1",
    "webpack-dev-server": "^2.4.5"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1"
  }

enter image description here

1 个答案:

答案 0 :(得分:2)

在App.js中你应该改变这个:

<Router>
    <div>
        <Match exactly pattern="/" component={Home} />
        <Match exactly pattern="/profile/:profileId" component={Profile} />
        <Miss component={NotFound} />
    </div>
</Router>

到此

<Router>
    <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/profile/:profileId" exact component={Profile}" />
        <Route component={NotFound} />
    </Switch>
</Router>

Switch元素用于在其中一个路线进行渲染时停止验证其他路线。

并且不要忘记从Route而不是Switch导入这些模块(BrowserRouterreact-router-domreact-router)。