React-Router Hooks

Route 写法1 <Route path="/child">  <Child /></Route>// 类似<Route path="/child" children={<Child />}></Route> children 组件使用一个特殊的 c...

Route

写法1

<Route path="/child">
  <Child />
</Route>
// 类似
<Route path="/child" children={<Child />}></Route>


children 组件使用一个特殊的 children prop 来将 Route 的子组件传递到渲染结果中。


写法2

<Route path="/child" component={Child}></Route>


component 属性引用一个 React 组件,可以是函数组件或者类组件。


写法3

<Route path="/child" render={() => (<div>Child</div>)}></Route>
// 类似写法2
<Route path="/child" component={() => (<div>Child</div>)}></Route>
// 类似写法1
<Route path="/child" children={<div>Child</div>}></Route>


render 这对于内联渲染很方便。具有 render prop 的组件接受一个函数,该函数返回一个 React 元素。


Hooks

React Router附带了一些挂钩,在组件内部调用这些钩子可以访问路由的状态。(React >= 16.8)


1、useHistory

2、useLocation

3、useParams

4、useRouteMatch


useHistory 该钩子提供对 history 对象的访问。 使用方法与使用props.history相同。

function HomeButton(props) {
  let history = props.history;
  function handleClick() {
    history.push("/home");
  }
  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}


新代码

function HomeButton() {
  let history = useHistory();
  function handleClick() {
    history.push("/home");
  }
  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}


useLocation 该挂钩提供对 location 对象的访问,这对于需要了解当前URL的任何组件很有用。

const LinkToFaqComponent = (props) => {
  return (
    <Link to=`${props.location.pathname}/faq`>
      Read Our FAQ Here!
    </Link>
  )
}
export const LinkToFaq = withRouter(LinkToFaqComponent)


新代码

const LinkToFaqComponent = (props) => {
  return (
    <Link to=`${props.location.pathname}/faq`>
      Read Our FAQ Here!
    </Link>
  )
}
export const LinkToFaq = withRouter(LinkToFaqComponent)
useParams 返回URL参数的键/值对的对象。 使用它来访问当前<Route>的match.params。
// Component A:
const ComponentA = (props) => {
  const { id } = props.match.params;
  return <ComponentB id={id} />;
}
export const RoutedComponentA = withRouter(ComponentA);
// Component B:
const ComponentB = (props) => (<div>My ID is: {props.id}</div>);


新代码

const ComponentA = () => {
  return <ComponentB />;
}
// Component B:
const ComponentB = () => {
  const { id } = useParams();
  return (<div>My ID is: {id}</div>);
}


useRouteMatch 当您只需要路由匹配数据而无需实际渲染路由时,可以使用此钩子。

function BlogPost() {
  return (
    <Route
      path="/blog/:slug"
      render={({ match }) => {
        // 你只想在匹配的URL但是不渲染任何内容
        return <div />;
      }}
    />
  );
}
import { useRouteMatch } from "react-router-dom";
function BlogPost() {
  let match = useRouteMatch("/blog/:slug");
  // 你只想在匹配的URL但是不渲染任何内容
  return <div />;
}

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
王凯
王凯

92 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. bngvitmrbj 0 文章