React-Router Hooks

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 />;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章