如何使用反应路由器?它显示警告

how to use react-router? it shows warnings

我在 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;

终于解决了问题! 我实际上在 Rails 框架和 react-rails gem 上使用 Ruby。 我想来自 gem 的反应文件与原始反应不同。 一旦我用从 npm 安装的 react 替换 react gem 文件,一切正常。

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

以下示例没有错误:

(我还有一个 gulpfile 使用 browserify 进行 babelify 转换 - 将 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 /> 17=] 模块。

docs 确实很有帮助 - 但您很容易因复杂性而超出其范围。我做过几个复杂的路线方案,都可以做。

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

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

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