react-router学习

来源:互联网 发布:学大福利知乎 编辑:程序博客网 时间:2024/06/13 05:33

关于react-router,我提出几个问题

看读者能否在下面官方文档中找出答案


1、带path="/" 的route对应的组件为什么要用this.props.chldren


2、为什么带path="/" 的route是嵌套其它route,为什么带path="/" 的route对应的组件才用<Link>元素


3、hashHistory是什么意思

                       我先解答这个问题,  #作为符号讲时读作hash,hashHistory表示,路由的切换由URL的hash变化决定,即URL的#部分发生变化。举例来说,用户访问http://www.example.com/,实际会看到的是http://www.example.com/#/

 



也就是说带path="/" 的route是其它route的父亲,对应的组件是其它组件的父亲

Configuration Components

<Route>

<Route> is used to declaratively map routes to your application's component hierarchy.

Props

path

The path used in the URL.

It will concat with the parent route's path unless it starts with /, making it an absolute path.

Note: Absolute paths may not be used in route config that is dynamically loaded.

If left undefined, the router will try to match the child routes.

component

A single component to be rendered when the route matches the URL. It can be rendered by the parent route component withthis.props.children.

const routes = (  <Route path="/" component={App}>    <Route path="groups" component={Groups} />    <Route path="users" component={Users} />  </Route>)class App extends React.Component {  render () {    return (      <div>        {/* this will be either <Users> or <Groups> */}        {this.props.children}      </div>    )  }}
components

Routes can define one or more named components as an object of [name]: component pairs to be rendered when the path matches the URL. They can be rendered by the parent route component with this.props[name].

// Think of it outside the context of the router - if you had pluggable// portions of your `render`, you might do it like this:// <App main={<Users />} sidebar={<UsersSidebar />} />const routes = (  <Route path="/" component={App}>    <Route path="groups" components={{main: Groups, sidebar: GroupsSidebar}} />    <Route path="users" components={{main: Users, sidebar: UsersSidebar}}>      <Route path=":userId" component={Profile} />    </Route>  </Route>)class App extends React.Component {  render () {    const { main, sidebar } = this.props    return (      <div>        <div className="Main">          {main}        </div>        <div className="Sidebar">          {sidebar}        </div>      </div>    )  }}class Users extends React.Component {  render () {    return (      <div>        {/* if at "/users/123" `children` will be <Profile> */}        {/* UsersSidebar will also get <Profile> as this.props.children,            so its a little weird, but you can decide which one wants            to continue with the nesting */}        {this.props.children}      </div>    )  }}

0 0