我正在使用“react@15.0.2”和“react-router@3.0.0”。
我有这个最小的例子而我无法使其发挥作用:
var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router');
var Route = Router.Route;
var Test = React.createClass({
render: function() {
return <h1>Test</h1>;
}
});
ReactDOM.render(
<Router>
<Route path="/" component={Test}/>
</Router>,
document.getElementById('app')
);
我知道<Test/>
没问题,因为ReactDOM.render(<Test/>, ...)
工作正常。
gulp编译它,但页面没有显示,控制台说:
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
at invariant (bundle.js:41330)
at ReactCompositeComponentWrapper.instantiateReactComponent [as _instantiateReactComponent] (bundle.js:39575)
at ReactCompositeComponentWrapper.performInitialMount (bundle.js:28233)
at ReactCompositeComponentWrapper.mountComponent (bundle.js:28160)
at ReactCompositeComponentWrapper.wrapper [as mountComponent] (bundle.js:35008)
at Object.mountComponent (bundle.js:35674)
at mountComponentIntoNode (bundle.js:33795)
at ReactReconcileTransaction.perform (bundle.js:38439)
at batchedMountComponentIntoNode (bundle.js:33816)
at ReactDefaultBatchingStrategyTransaction.perform (bundle.js:38439)
编辑:index.htm
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bundle.css" />
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<!--ALL REACT CODE-->
<div id="app"></div>
<!--ALL REACT CODE-->
<script src="scripts/bundle.js"></script>
</body>
</html>
答案 0 :(得分:2)
尝试将作为第一个参数传递的<Router>
元素包装到括号中的render()
中:
var Test = React.createClass({
render: function() {
return (<h1>Test</h1>);
}
});
ReactDOM.render((
<Router>
<Route path="/" component={Test}/>
</Router>
), document.getElementById('app'));
可能只是解析问题。
同时尝试更新require
react-router
语句。对于非ES6版本,每react-router installation instructions为语句末尾添加.Router
。
希望这有帮助!
var Router = require('react-router').Router;
答案 1 :(得分:0)
是的,就像上面提到的评论一样,答案没有指定浏览器历史记录部分。
var React = require("react");
var ReactDOM = require("react-dom");
var SchoolsList = require("./components/SchoolsList.jsx");
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var Link = require('react-router').Link
var browserHistory = require('react-router').browserHistory;
var _question = schoolsStore.getQuestion();
function render(){
//console.log(_question);
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={SchoolsList} question={_question.question} activeIndex={_question.activeIndex} />
</Router>,
document.getElementById("container"));
}
render();