如何使用 react-router?它显示警告
我使用 CommonJS 的以下依赖项。
我尝试同时渲染 App 和 Home。
Home 组件应仅在
DefaultRoute
的路径为
path="/"
或
path="home"
时渲染。
但由于某些原因,我收到很多警告。
我遗漏了什么?
我花了几天时间遵循一堆示例和教程。
任何提示或解决方案都将不胜感激。
package.json
"dependencies": {
"browserify": "~> 10.2.4",
"browserify-incremental": "^3.0.1",
"coffeeify": "~> 0.6",
"events": "^1.0.2",
"flux": "^2.0.3",
"i18next-client": "^1.10.2",
"object-assign": "^3.0.0",
"react": "^0.13.3",
"react-router": "^0.13.3",
"reactify": "^1.1.1"
}
app.js
var Main = require("./main.js");
var Router = require("react-router");
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var Home = require("./components/home.js.jsx");
var App = React.createClass({
getInitialState: function(){
return {
signedIn: null,
currentUser: null
};
},
componentWillMount: function(){
$.ajax({
url: "/is_signed_in",
method: "GET",
dataType: "json"
}).success(function(response){
this.setSignedIn(response);
}.bind(this));
},
componentDidMount: function(){
Main();
},
setSignedIn: function(response){
this.setState({ signedIn: response.signed_in, currentUser: $.parseJSON(response.current_user) });
console.log(Home);
},
render: function(){
// <RouteHandler signedIn={this.state.signedIn} />
return (<RouteHandler />);
}
});
// React.render(<App />, document.body);
var routes = (
<Route handler={App}>
<DefaultRoute handler={Home} />
</Route>
);
Router.run(routes, function(Handler){
React.render(<Handler/>, document.body);
});
日志
Warning: Failed Context Types: Required context `routeDepth` was not specified in `RouteHandler`. Check the render method of `App`.
Warning: Failed Context Types: Required context `router` was not specified in `RouteHandler`. Check the render method of `App`.
Warning: owner-based and parent-based contexts differ (values: `undefined` vs `1`) for key (routeDepth) while mounting RouteHandler (see: http://fb.me/react-context-by-parent)
Warning: owner-based and parent-based contexts differ (values: `undefined` vs `function (props, context) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ("production" !== "development") {
("production" !== "development" ? warning(
this instanceof Constructor,
'Something is calling a React component directly. Use a factory or ' +
'JSX instead. See: https://fb.me/react-legacyfactory'
) : null);
}
// Wire up auto-binding
if (this.__reactAutoBindMap) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if ("production" !== "development") {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof initialState === 'undefined' &&
this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
("production" !== "development" ? invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.getInitialState(): must return an object or null',
Constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof initialState === 'object' && !Array.isArray(initialState)));
this.state = initialState;
}`) for key (router) while mounting RouteHandler (see: http://fb.me/react-context-by-parent)
Uncaught TypeError: Cannot read property 'getRouteAtDepth' of undefined
Warning: Failed Context Types: Required context `routeDepth` was not specified in `RouteHandler`. Check the render method of `App`.
Warning: Failed Context Types: Required context `router` was not specified in `RouteHandler`. Check the render method of `App`.
Warning: owner-based and parent-based contexts differ (values: `undefined` vs `1`) for key (routeDepth) while mounting RouteHandler (see: http://fb.me/react-context-by-parent)
Warning: owner-based and parent-based contexts differ (values: `undefined` vs `function (props, context) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ("production" !== "development") {
("production" !== "development" ? warning(
this instanceof Constructor,
'Something is calling a React component directly. Use a factory or ' +
'JSX instead. See: https://fb.me/react-legacyfactory'
) : null);
}
// Wire up auto-binding
if (this.__reactAutoBindMap) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if ("production" !== "development") {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof initialState === 'undefined' &&
this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
("production" !== "development" ? invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.getInitialState(): must return an object or null',
Constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof initialState === 'object' && !Array.isArray(initialState)));
this.state = initialState;
}`) for key (router) while mounting RouteHandler (see: http://fb.me/react-context-by-parent)
Uncaught TypeError: Cannot read property '_currentElement' of null
home.js.jsx
var home = function(){
var HomeHero = React.createClass({
componentWillMount: function() {
document.getElementsByClassName("homeHero")[0].className = "homeHero container header pure-u-1 u-size1040";
},
render: function() {
return(
<div className="hero textAlignCenter">
<h1 className="hero-logo"><a href="/">LOGO</a></h1>
<h2 className="hero-description">DESCRIPTION.</h2>
</div>
);
}
});
var Home = React.createClass({
render: function() {
return (
<div>
Home
</div>
);
}
});
React.render(<HomeHero />, document.getElementsByClassName("homeHero")[0]);
React.render(<Home />, document.getElementsByClassName("home")[0]);
};
module.exports = home;
终于解决了问题!
我实际上使用 Ruby on Rails 框架和
react-rails
gem。
我猜想 gem 中的 react 文件与原始 react 不同。
当我用从 npm 安装的
react
替换
react gem
文件后,一切正常。
该死的……我花了好几天才弄清楚。 感谢大家的回答。
以下示例可无错误运行:
(我还有一个 gulpfile 使用 browserify 进行 babelify 转换 - 将
react
和
react-router
放入名为
vendors.js
的单独文件中 - 此处省略)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testing</title>
</head>
<body>
</body>
<script type="text/javascript" src="dist/vendors.js"></script>
<script type="text/javascript" src="dist/app.js"></script>
</html>
app.jsx
var React = require('react');
var Router = require('react-router');
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var Home = React.createClass({
render: function(){
return (
<h1>Home</h1>
)
}
});
var App = React.createClass({
render: function(){
return (
<div>
<RouteHandler />
</div>
)
}
});
var routes = (
<Route path='/' handler={App}>
<DefaultRoute handler={Home} />
</Route>
);
Router.run(routes, function(Handler){
React.render(<Handler/>, document.body);
});
react-router
为您处理大部分繁重工作。如果您想渲染到其他位置,请在渲染中更改。
Router.run(routes, function(Handler){
React.render(<Handler/>, document.getElementById('someId'));
});
使用您添加的
home
代码,如果您想在那里使用路由器,您也可以按照与上述类似的模式进行操作,并向
home
模块添加
<RouteHandler />
。
文档 非常有用 - 但由于您的复杂性,很容易超出其范围。我已经完成了一些复杂的路线方案 - 所有这些都可以完成。
编辑 在此处添加了一个 repo - https://github.com/kellyjandrews/react-touter-testing
我继续并包含了所有节点模块 - 主要是因为我很懒,没有验证我的
package.json
。应该能够从文件夹运行
gulp
,您将在浏览器中看到“Home”。如果您收到警告 - 您发生了一些我无法从这里修复的事情。
这是因为您正在具有 react-router 的组件外部进行渲染。请参阅您的主页组件。您应该让
<RouteHandler />
进行渲染以传递上下文变量。希望有所帮助