请解释如何使用 React Context API 配合自定义路由组件来实现全局路由状态管理,举例说明其应用场景。

答案:

在React应用中,全局路由状态管理是确保应用中任何组件都能访问到当前路由信息的一种方法。这在大型应用中特别有用,因为它能避免通过props穿插传递路由信息。React Context API结合自定义路由组件可以很好地实现这一需求。

1. 创建 Context

首先,我们需要创建一个Context,这个Context将用于存储路由信息,如路径、参数等。

import React, {createContext, useState} from 'react';

// 创建路由Context
export const RouterContext = createContext();

// 自定义路由Provider组件
export const RouterProvider = ({ children }) => {
  const [route, setRoute] = useState({ path: '/', params: {} });

  // 更新路由信息的方法
  const updateRoute = (newPath, newParams) => {
    setRoute({ path: newPath, params: newParams });
  };

  return (
    <RouterContext.Provider value={{ route, updateRoute }}>
      {children}
    </RouterContext.Provider>
  );
};

2. 使用自定义路由组件

接下来,创建一个自定义路由组件,该组件在切换路由时更新Context中的路由信息。

import React from 'react';
import { useHistory } from 'react-router-dom';
import { RouterContext } from './RouterContext';

// 自定义路由组件
const CustomRoute = ({ path, component: Component, ...rest }) => {
  const history = useHistory();
  const { updateRoute } = React.useContext(RouterContext);

  // 监听路由变化并更新Context
  React.useEffect(() => {
    const unlisten = history.listen((location, action) => {
      const { search, hash, pathname } = location;
      const params = new URLSearchParams(search);
      updateRoute(pathname, Object.fromEntries(params));
    });
    return () => unlisten();
  }, [history, updateRoute]);

  return (
    <Route
      {...rest}
      path={path}
      render={(props) => <Component {...props} />}
    />
  );
};

3. 应用场景

动态面包屑导航

在大型应用中,导航栏通常需要显示当前路径的面包屑导航。通过全局路由状态管理,我们可以轻松获取当前路径信息,从而动态生成面包屑导航。

import React from 'react';
import { RouterContext } from './RouterContext';

const Breadcrumb = () => {
  const { route } = React.useContext(RouterContext);

  // 根据当前路径生成面包屑
  const breadcrumbs = route.path.split('/').filter(Boolean).map((part, index) => (
    <span key={index}>{part}</span>
  ));

  return <nav>{breadcrumbs}</nav>;
};

权限控制

在某些情况下,应用需要根据用户的权限来显示或隐藏某些路由。通过全局路由状态管理,可以在路由切换时检查用户的权限,并根据权限动态显示或隐藏路由。

const ProtectedRoute = ({ path, component: Component, ...rest }) => {
  const { route, updateRoute } = React.useContext(RouterContext);
  const [isAuthenticated, setIsAuthenticated] = React.useState(false);

  // 检查用户权限
  if (!isAuthenticated) {
    return <Redirect to='/login' />;
  }

  return (
    <Route
      {...rest}
      path={path}
      render={(props) => <Component {...props} />}
    />
  );
};

通过这种方式,我们可以高效地管理应用中的路由状态,使得路由信息能够被应用中的任意组件访问,从而构建更加灵活和可维护的应用。