【问题标题】:how to use react-router? it shows warnings如何使用反应路由器?它显示警告
【发布时间】:2015-11-04 13:18:08
【问题描述】:

我在 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 的反应文件与原始反应不同。 一旦我用从 npm 安装的 react 替换 react gem 文件,一切正常。

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

【问题讨论】:

    标签: javascript reactjs browserify reactjs-flux react-router


    【解决方案1】:

    以下示例可以正常运行:

    (我还有一个 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 代码,如果您想在那里有一个路由器,您也可以按照与上述类似的模式执行此操作,并将&lt;RouteHandler /&gt; 添加到home 模块。

    docs 确实很有帮助 - 但由于您的复杂性,很容易超出他们的范围。我做过一些复杂的路线方案——都可以做到。

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

    我继续并包含所有节点模块 - 主要是因为我很懒并且没有验证我的 package.json。应该能够从文件夹中运行gulp,您将在浏览器中看到“主页”。如果您因此收到警告 - 您有一些我无法从这里解决的问题。

    【讨论】:

    • 我的 react-router 和 react 是 ^0.13.3。如果您阅读github.com/rackt/react-router/issues/638 的最后一条评论,React Router 0.13 支持 React 0.13。当我遵循您的代码时,我遇到了同样的错误..
    • 可能是您的主模块有问题。让我得到一些对我有用的东西。
    • 我在这个问题上添加了我清理过的 home.js.jsx。我想我找到了问题所在。我已经在home.js.jsx 中渲染了“home”组件。但我想在不同的父节点呈现组件,而不是在document.body。是否有解决方法可以在 Router.run 中为子组件自定义 React.render
    • 你不需要这样做——这真的取决于你想要完成什么。我有一个可以构建的简化示例。我会尽快更新。
    • 已更新 - 这是一个非常简单的示例 - 但我的控制台上没有错误。从这里开始,这应该回答有关修复错误的问题。为您开始遇到的其他问题打开一个新问题。一定要慢慢开始,然后逐步向上。在这里很容易迷路。
    【解决方案2】:

    这是因为您在具有 react-router 的组件之外进行渲染。查看您的家庭组件。您应该让&lt;RouteHandler /&gt; 进行渲染以传递上下文变量。希望有帮助

    【讨论】:

    • 进行渲染是什么意思?那你的意思是我不应该在 app.js.jsx 中使用 react-router?
    • 我的意思是在你家里。 react.render 应该被省略。只有渲染功能。 export const Home = React.createClass({ render() { return &lt;div&gt;This is my Home Component&lt;/div&gt;} }); 然后导入到app.js.jsx中
    • 不。那不是问题。当我删除 react-rails gem 并使用 node 包 react 时,它起作用了
    • 我怀疑这会起作用,因为您的家会呈现自己的组件。如果你把 react-router 标签放在上面,肯定会失败。比如添加&lt;Link&gt; &lt;RouteHandler&gt; 等等。但在修复方面做得很好:)
    • 哦,我明白你的意思了。我没有遵循该代码。这只是示例代码。我有自己的生产代码。
    猜你喜欢
    • 2017-01-16
    • 2019-01-07
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2021-11-06
    • 2018-03-22
    • 2016-11-28
    相关资源
    最近更新 更多