• React-router(摘记)


    react-router被拆分为react-routerreact-router-domreact-router-native三部分

    一级路由:

    import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom'

    class App extends Component { render() { return ( <Router basename='/route'> <div> <Route path="/" exact component={Home}></Route> <Route path="/mime" render={({match}) => <div>Home</div>}></Route>
          // 和render是一样的功能,不过它不论是否匹配到都会调用
          <Route path="/list" children={({match})=>(...)}></Route>
          <ul> 
           // replace:基本不用,为true时会替换掉上次访问的地址

            // exact:如果为true,只有当访问地址严格匹配时才会使用激活样式。

            // strict:如果为true,只有挡访问地址后的斜杠严格匹配(有或没有)才会使用激活样式。

            // isActive:跟一个函数,当导航激活时要做的事情。


            <li> <Link to="/" replace="true">home</Link> </li>
            <li> <Link to="/mime">mime</Link> </li>
            <li> <Link to="/list">list</Link> </li>
            <li>
    <Link to={{
      pathname: '/list',
      search: '?sort=name',
      state: { id: 2 }
    }} />
            </li>
          </ul>
        </div>
      </Router> );
      }
    }

    二级路由:

    export default class List extends React.Component {
      constructor(props) {
        super(props);
      }
      render() {
        return (
          <div>
            <h1>列表页</h1>
            <ul>
              <li>
                <Link to={`${this.props.match.url}/details`}>详情</Link>
              </li>
              <li>
                <Link to={`${this.props.match.url}/edit`}>编辑</Link>
              </li>
        </ul>
    <Route path={`${this.props.match.url}/details`} component={Details} /> 
    <Route path={`${this.props.match.url}/edit`} component={Edit} /> </div> ); } }

    带参数

    <Route
        path={`${this.props.match.url}/:id(20|100)`}
        component={Details}
    />

    获取对应的参数

    <h1>{this.props.match.params.id}</h1>

    导航link

    <NavLink to="/mime" activeClassName='actvived'>mime</NavLink>
    
    <NavLink to="/mime" activeStyle={{color: red,fontSize: 20px}}>mime</NavLink>

    静态路由:StaticRouter

    //  只会渲染一次,而且不会直接地对用户的交互操作做出反应

    import { createServer } from 'http'
    import React from 'react'
    import ReactDOMServer from 'react-dom/server'
    import { StaticRouter } from 'react-router'
    
    createServer((req, res) => {
      // 这个context包含渲染的结果
      const context = {}
      const html = ReactDOMServer.renderToString(
        <StaticRouter location={req.url} context={context}>
          <App/>
        </StaticRouter>
      )
    
      // 如果使用<Redirect>,context.url将包含要重定向到的URL
      if (context.url) {
        res.writeHead(302, {
          Location: context.url
        })
        res.end()
      } else {
        res.write(html)
        res.end()
      }
    }).listen(3000)
    // basename:所有位置的基本url,正确的格式应该是前面有/后面没有/。
    
    <StaticRouter basename="/main">
      <Link to="/list"/> <!--渲染出来应该是<a href="/main/list">-->
    </StaticRouter>
    // location:如果是个字符串就应该是服务器上收到的url(req.url)。如果是个对象应该是一个类似{pathname, search, hash, state}的位置对象。
    
    <StaticRouter location={{ pathname: '/home' }}>
      <App/>
    </StaticRouter>
    //context: 一个普通js对象,在渲染过程中组件可以向对象里添属性以存储有关渲染的信息
    
    //app上有个404组件,把status改成404
    const NotFound = () => (
      <Route
        render={({ staticContext }) => {
          if (staticContext) {
            staticContext.status = 404;
          }
          return (
            <div>
              <h1>你输入的地址不正确哟!</h1>
            </div>
          );
        }}
      />
    );
    
    // 在服务端我们就可以通过判断,对这个404界面发送404响应
    const context = {};
    const content = renderToString(
        <Provider store={store}>
            <StaticRouter location={req.url} context={context}>
                <App />
            </StaticRouter>
        </Provider>
    );
    if (context.status === 404) {
        res.status(404);
    }
    // 判断重定向,如果有context.url就说明应用被重定向,这允许我们从服务器发送适当的重定向。
    
    if (context.url) {
      // can use the `context.status` that
      // we added in RedirectWithStatus
      redirect(context.status, context.url)
    }

    <Switch>

    // 用来包裹Route或者Redirect组件,而且不能放其他元素,
    // 用来渲染第一个匹配到的路由,不会向下继续匹配。
    // 如果不用Switch包裹的话,访问/about时下面三个组件都会被渲染
    
    <Route path="/about" component={About}/>
    <Route path="/:user" component={User}/>
    <Route component={NoMatch}/>

    Redirect

    // 将匹配到的路径重定向到一个新的地址。
    // 新的地址应该覆盖掉访问的地址
    // from:匹配到的访问的地址
    // to:重定向到的地址
    // push:为true时,重定向到的地址会添加到历史访问记录,并且无法回到之前访问的地址。
    
    <Route path="/game" component={Game}></Route>
    <Redirect from="/home" to="game" push={true}></Redirect>

    <withRouter>

    // withRouter可以用来包装任何自定义组件,并将historylocationmatch三个对象传入。这样组件就可以拿到路由信息。

    import {withRouter} from 'react-router-dom';
    const Home = withRouter(({history,location,match})=>{
      return <h1>{location.pathname}</h1>
    })

    <history>

    length:获取历史堆栈中的条目数
    
    action:获取当前操作(push/pop/replace)
    
    location:获取当前位置,包括(pathname、search、hash、state、)
    
    push(''):添加一个新的条目到历史堆栈(一般会用来跳转到一个新页面)
    
    replace(''):替换掉当前堆栈上的条目
    
    go(n):通过n个条目移动历史堆栈中的指针,向前或向后n个
    
    goBack():后退一个历史条目,相当于go(-1)。
    
    goForward():前进一个历史条目,相当于go(1)
    
    block:防止导航
  • 相关阅读:
    小程序 页面跳转
    mybatis 字段类型Data相
    数据库的重命名
    validator js验证器
    git命令
    常用正则表达式
    Vuejs+elementUI项目,在进行打包时,要注意的问题
    多线程的sleep、yield、join用法及sleep与wait的区别
    跨域请求问题:CORS
    spring框架中用到了哪些设计模式
  • 原文地址:https://www.cnblogs.com/uh-huh/p/11911437.html
Copyright © 2020-2023  润新知