如何在 TypeScript 中使用 navigation.replace?

6 javascript typescript reactjs react-native react-navigation

我试图在我的代码中使用它:

const navigation = useNavigation();
navigation.replace('AllFriends')
Run Code Online (Sandbox Code Playgroud)

但我不断收到错误消息:

Property 'replace' does not exist on type 'NavigationProp<Record<string, object | undefined>, string, NavigationState, {}, {}>'.
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用这个

const navigation =  useNavigation<StackNavigationProp<{route: {} }>>()
navigation.replace('route');
Run Code Online (Sandbox Code Playgroud)

如此处建议的:https ://github.com/react-navigation/react-navigation/issues/8256

但这给了我一个错误,即替换预期有 2 个参数,但只得到 1 个...

我正在使用 "@react-navigation/native": "^5.5.1",

cal*_*wan 12

替换方法仅适用于 StackNavigators 中的屏幕。我们需要一种方法来明确地键入屏幕是这样的。

当您实例化您的 StackNavigator 时,您可以传入一个类型来定义您的路由及其期望接收的参数:

export type StackParams = {
   MyRoute: undefined;
   AnotherRoute: {
      id: number
   }
}

createStackNavigator<StackParams>();
Run Code Online (Sandbox Code Playgroud)

然后在屏幕中将该参数列表传递给StackNavigationProp

import { StackNavigationProp } from '@react-navigation/stack/';
import { StackParams} form 'your/routes';

const navigation =  useNavigation<StackNavigationProp<StackParams>>()
navigation.replace('route');
Run Code Online (Sandbox Code Playgroud)

这样做可以确认这是一个堆栈屏幕,并提供了您可以导航到的路线列表:

replace('AnotherRoute') //success!
replace('FakeRoute') //error, this was not defined in our RouteParams
Run Code Online (Sandbox Code Playgroud)


小智 5

const navigation =  useNavigation<StackNavigationProp<{route: {} }>>()
navigation.replace('route');
Run Code Online (Sandbox Code Playgroud)


Aur*_*aty 5

如此处所述: https: //github.com/react-navigation/react-navigation/issues/7820#issuecomment-689646876

最简单的方法是这样的:

const navigation = useNavigation<StackNavigationProp<ParamListBase>>();
Run Code Online (Sandbox Code Playgroud)