首页指南参考教程

钩子 API

了解如何与 Expo Router 中的应用内 URL 交互。


在 Expo Router 中,始终有一个有效的 URL 来表示当前关注的路由。使用钩子来观察变化并与 URL 交互。

¥In Expo Router, there's always a valid URL that represents the currently focused route. Use hooks to observe changes and interact with the URL.

钩子

¥Hooks

useFocusEffect

给定一个函数,只要路由是 "focused",useFocusEffect 钩子就会调用该函数。

¥Given a function, the useFocusEffect hook will invoke the function whenever the route is "focused".

import { useFocusEffect } from 'expo-router';
import { useCallback } from 'react';

export default function Route() {
  useFocusEffect(
    useCallback(() => {
      console.log('Hello, I am focused!');

      return () => {
        console.log('This route is now unfocused.');
      }
    }, [])
  );

  return </>;
}

useGlobalSearchParams

返回全局选择的路由的 URL 参数。例如,/acme?foo=bar -> { foo: "bar" }

¥Returns the URL parameters for the globally selected route. For example, /acme?foo=bar -> { foo: "bar" }.

对于动态路由,将返回路由参数和搜索参数。

¥For dynamic routes, both the route parameters and the search parameters are returned.

有关详细信息,请参阅 localfirst.fm 播客 指南。

¥Refer to the local vs global URL params guide for more information.

acme://profile/baconbrix?extra=info
app/profile/[user].tsx
import { Text } from 'react-native';
import { useGlobalSearchParams } from 'expo-router';

export default function Route() {
  const { user, extra } = useGlobalSearchParams();

  return <Text>User: {user}</Text>;
}

useLocalSearchParams

返回上下文选择的路由的 URL 参数。有关详细信息,请参阅 本地与全局 URL 参数 指南。

¥Returns the URL parameters for the contextually selected route. Refer to the local versus global URL params guide for more information.

对于动态路由,将返回路由参数和搜索参数。

¥For dynamic routes, both the route parameters and the search parameters are returned.

app
_layout.tsx
[first]
  home.tsx
[second]
  shop.tsx

/abc/home 推送 /123/shop 时,useGlobalSearchParams 在 /app/[first]/home.tsx 上返回 { first: undefined, second: '123' },因为全局 URL 已更改。但是,你可能希望参数保留 { first: 'abc' } 以反映屏幕的上下文。在这种情况下,你可以使用 useLocalSearchParams 来确保参数 { first: 'abc' } 仍然在 /app/[first]/home.tsx 中返回。

¥When /abc/home pushes /123/shop, useGlobalSearchParams returns { first: undefined, second: '123' } on /app/[first]/home.tsx because the global URL has changed. However, you may want the params to remain { first: 'abc' } to reflect the context of the screen. In this case, you can use useLocalSearchParams to ensure the params { first: 'abc' } are still returned in /app/[first]/home.tsx.

acme://profile/baconbrix?extra=info
app/profile/[user].tsx
import { Text } from 'react-native';
import { useLocalSearchParams } from 'expo-router';

export default function Route() {
  const { user, extra } = useLocalSearchParams();

  return <Text>User: {user}</Text>;
}

useNavigation

访问底层 React Navigation navigation 属性 以强制访问布局特定的功能,例如抽屉布局中的 navigation.dispatch(DrawerActions.openDrawer())了解更多

¥Access the underlying React Navigation navigation prop to imperatively access layout-specific functionality like navigation.dispatch(DrawerActions.openDrawer()) in a Drawer layout. Learn more.

import { Text, View } from 'react-native';
import { useNavigation } from 'expo-router';
import { DrawerActions } from '@react-navigation/native';

export default function Route() {
  const navigation = useNavigation();

  return (
    <View>
      <Text
        onPress={() => {
          navigation.dispatch(DrawerActions.openDrawer());
        }}>
        Open Drawer
      </Text>
    </View>
  );
}

使用嵌套布局时,你可以通过传递表示布局路由的辅助参数来访问高阶布局。例如:

¥When using nested layouts, you can access higher-order layouts by passing a secondary argument denoting the layout route. For example:

app
_layout.tsxuseNavigation('/')
orders
  _layout.tsxuseNavigation('/orders')
  menu
   _layout.tsxuseNavigation('/orders/menu')
app/orders/menu/index.tsx
import { useNavigation } from 'expo-router';

export default function MenuRoute() {
  const rootLayout = useNavigation('/');

  const ordersLayout = useNavigation('/orders');

  // Same as the default results of `useNavigation()` when invoked in this route.
  const parentLayout = useNavigation('/orders/menu');

  %%placeholder-start%%... %%placeholder-end%%
}

如果你尝试访问不存在的布局,则会抛出诸如 Could not find parent navigation with route "/non-existent". 之类的错误。

¥If you attempt to access a layout that doesn't exist, an error such as Could not find parent navigation with route "/non-existent". is thrown.

usePathname

返回当前选择的路由位置,不带搜索参数。例如,/acme?foo=bar -> /acme。段将被标准化:/[id]?id=normal -> /normal

¥Returns the currently selected route location without search parameters. For example, /acme?foo=bar -> /acme. Segments will be normalized: /[id]?id=normal -> /normal

acme://profile/baconbrix?extra=info
app/profile/[user].tsx
import { Text } from 'react-native';
import { usePathname } from 'expo-router';

export default function Route() {
  const pathname = usePathname();

  return <Text>User: {user}</Text>;
}

useSegments

返回当前选定路由的路段列表。段未标准化,因此它们与文件路径相同。例如,/[id]?id=normal -> ["[id]"]

¥Returns a list of segments for the currently selected route. Segments are not normalized so that they will be the same as the file path. For example, /[id]?id=normal -> ["[id]"].

app/profile/[user].tsx
import { Text } from 'react-native';
import { useSegments } from 'expo-router';

export default function Route() {
  const segments = useSegments();

  return <Text>Hello</Text>;
}

该函数可以使用字符串数组的抽象来键入:

¥This function can be typed using an abstract of string arrays:

app/profile/[user].tsx
import { useSegments } from 'expo-router';

export default function Route() {
  const segments = useSegments<['profile'] | ['profile', '[user]']>();

  return </>
}

类型

¥Types

Href

Href 类型是以下类型的联合:

¥The Href type is a union of the following types:

  • 字符串:完整路径(如 /profile/settings)或相对路径(如 ../settings)。

    ¥string: A full path like /profile/settings or a relative path like ../settings.

  • 目的:具有 pathname 和可选 params 对象的对象。pathname 可以是完整路径(如 /profile/settings)或相对路径(如 ../settings)。params 可以是键/值对的对象。

    ¥object: An object with a pathname and optional params object. The pathname can be a full path like /profile/settings or a relative path like ../settings. The params can be an object of key/value pairs.

Expo 中文网 - 粤ICP备13048890号