【问题标题】:React- Router, making sense of the transitionsReact-Router,理解转换
【发布时间】:2015-09-20 11:35:32
【问题描述】:

我使用过 Angular 和 Flask,也使用过路由和转换,但是 React-Router 的工作方式有些令人困惑。

例如来自介绍页面https://github.com/rackt/react-router/blob/master/docs/Introduction.md

React.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
      <Route path="inbox" component={Inbox}>
        {/* Add the route, nested where we want the UI to nest */}
        <Route path="messages/:id" component={Message} />
      </Route>
    </Route>
  </Router>
), document.body)

这段代码嵌套的方式让我很难看到它并告诉你根据我们当前所在的 URL 路径将呈现什么。

例如,“/”部分总是要渲染还是仅在我们处于顶级端点时渲染?

“关于”和“收件箱”是一起呈现还是两者兼而有之?

对不起,如果这对某些人来说非常明显。这让我有点绊倒了太久了,所以我想问问你们。 :)

【问题讨论】:

    标签: javascript reactjs react-router url-routing flux


    【解决方案1】:

    给定以下App 组件:

    var App = React.createClass({
      render() {
        return (
          <div>
            <h1>App title</h1>
            {this.props.children}
          </div>
        );
      }
    });
    

    点击/ 会渲染该组件,而this.props.childrenundefined

    点击/about,路由器首先解析/,所以App组件再次渲染,和之前一样。

    从那里,路由器向下钻取路由层次结构,查看是否有任何路径与字符串的其余部分匹配,即about。还有:

    &lt;Route path="about" component={About} /&gt;

    这条路由是App的直接子级,所以this.props.children现在是About组件,因为我们选择在App中渲染this.props.children,所以会被渲染。

    【讨论】:

    • 这是否意味着“/”总是被渲染?这是否意味着 URL 应该是“....../inbox”或“....../about”?是否也意味着每次请求“....../about”时,URL 也应该有 ......./about/#/user/13425 以便我可以找到正确的用户数据也填充“消息”组件?
    • 1) 是 2) 不确定您的意思,但您不能同时请求 /inbox/about 3) 将 id 定义为您的路线中的参数,如下所示:如果您请求/about/user/13425messages/:id 允许从Message 检索与this.props.params.id 对应的值。请求不带参数的/about 将不会呈现Message,因为About 组件中的this.props.children 将是undefined
    猜你喜欢
    • 2015-05-03
    • 1970-01-01
    • 2018-12-29
    • 2015-11-14
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多