React.js - 元素类型无效

时间:2017-01-02 19:39:03

标签: javascript node.js reactjs express react-router

我使用react-router定义了路由并访问了该网址 然后,出现错误“元素类型无效”。

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

RouterRoute未定义。
你有什么想法来解决它吗?

index.js

var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router');
var Route = Router.Route;

var App = React.createClass({
    render: function() {
        return (
            <div>
                {this.props.children}
            </div>
        );
    }
});

var Users = React.createClass({/*...*/});
var User = React.createClass({/*...*/});

var routes = (
    <Route name="app" path="app" handler={App}>
        <Route name="users" path="users" handler={Users}>
            <Route name="user" path="/user/:userId" handler={User} />
        </Route>
    </Route>
);

ReactDOM.render(
    <Router>{routes}</Router>, document.getElementById('root')
);

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
    <div id="root"></div>
    <script src="./public/bundle.js"></script>
</body>
</html>

server.js

var express = require('express');
var app = express();
var http = require('http').Server(app);

app.get('/app/*', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});
app.get('/public/bundle.js', function(req, res) {
    res.sendFile(__dirname + '/public/bundle.js');
});

http.listen(3000, function() {
    console.log('Server listen at port 3000');
});

1 个答案:

答案 0 :(得分:0)

我认为你错过了定义根路线。

替换它

<Route path="/" handler={App}>
     <Route name="app" path="app" handler={App}>
        <Route name="users" path="users" handler={Users}>
            <Route name="user" path="/user/:userId" handler={User} />
        </Route>
    </Route>
</Route>