如何使用react-router?它显示警告

how to use react-router? it shows warnings

本文关键字:显示 警告 何使用 react-router      更新时间:2023-09-26

我在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不同。只要我把react gem文件替换为从npm安装的react,一切就正常了。

该死的……我花了好几天才弄明白。谢谢大家的回答。

下面的例子没有错误:

(我也有一个gulpfile做babelify转换与browserify -把reactreact-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代码,如果您想在那里有一个路由器,您也可以按照上面的类似模式这样做,并将<RouteHandler />添加到home模块。

文档确实很有帮助-但是很容易超出您的复杂性范围。我做过一些复杂的路线方案——都可以完成。

编辑在这里添加了一个repo - https://github.com/kellyjandrews/react-touter-testing

我继续并包括所有的节点模块-主要是因为我很懒,没有验证我的package.json。应该能够从文件夹中运行gulp,并且您将在浏览器中看到"Home"。如果你从这里得到警告-你有一些事情发生了,我不能从这里修复

这是因为你是在具有react-router的组件之外进行渲染的。查看您的home组件。你应该让<RouteHandler />做渲染来传递上下文变量。希望帮助