在反应导航中,如何替换堆栈中的最后两个屏幕?
例如,如果我当前的堆栈是screen1 -> screen2 -> screen3
,当我在screen3上调用.replace('screen4')
时,它变成screen1 -> screen2 -> screen4
但是我想办法让它变成screen1 -> screen4
您需要使用reset
来做到这一点:
import { CommonActions } from "@react-navigation/native";
// ...
navigation.dispatch(state => {
// Remove the last 2 routes from current list of routes
const routes = state.routes.slice(0, -2);
// Reset the state to the new state with updated list of routes
return StackActions.reset({
...state,
index: routes.length - 1,
routes
});
});