NavGraphBuilder 中的可组合项重复 3 次或更多次

Composable in NavGraphBuilder is repeating 3 or more times

我在 NavGraph 中调用我的可组合项时遇到问题,它重复 3 次,有时甚至更多次。我查看了调用的位置,但没有看到任何循环或其他内容。

NavGraph

fun NavGraphBuilder.addScheduleDetails(
    navController: NavHostController,
    userDataViewModel: UserDataViewModel,
    titulos: MutableState<String>,
    datosViewModel: DatosViewModel,
){
    val animationState = mutableStateOf(true)
    composable(route = MainDestinations.SCHEDULE_DETAILS_ROUTE+"/{${NavArguments.NOMBRE_HORARIO}}")
    {backStackEntry ->

            Log.w("Call", "ScheduleDetails")
            titulos.value = backStackEntry.arguments?.getString(NavArguments.NOMBRE_HORARIO)!!+" "
            val actions = MainActions(navController = navController)

            DetallesHorarioScreen(
                nombreHorario = backStackEntry.arguments?.getString(NavArguments.NOMBRE_HORARIO),
                userDataViewModel = userDataViewModel,
                onNavToAddSubject = actions.navigateToAgregarMateria,
                datosViewModel = datosViewModel,
                animationState = animationState
            )
    }
}

从 LOG 打印

2022-01-06 19:57:01.548 30533-30533/horarios W/Call: ScheduleDetails
2022-01-06 19:57:01.613 30533-30533/horarios W/Call: ScheduleDetails
2022-01-06 19:57:01.987 30533-30533/horarios W/Call: ScheduleDetails

致电composable(route = MainDestinations.SCHEDULE_DETAILS_ROUTE ...)

Card(
        modifier = Modifier
            .fillMaxWidth()
            .height(80.dp)
            .padding(10.dp)
            .clickable { onNavToHorario(nombre) },        //Call to navigator
        border = BorderStroke(width = 1.dp, color = primaryColorCustom),
        shape = RoundedCornerShape(10),
        backgroundColor = Color.White,
        elevation = 4.dp
    ) {...}

onNavToHorario()

val actions  = MainActions(navController = navController)
(...)
onNavToHorario = actions.navigateToHorario

MainActions()

class MainActions(navController: NavHostController){
    val navigateToHorario:(String) -> Unit = {nomHorario: String ->
        navController.navigate(route = MainDestinations.SCHEDULE_DETAILS_ROUTE+"/${nomHorario}")
    }
}

在其他情况下,我遇到了类似的问题,并且是动画引起的,但我已经删除了 NavGraph 中的所有动画,但问题仍然存在

导航总是淡入淡出目的地,因此每个屏幕总是会重组多次。这是预期的 Thinking in Compose guide:

In some cases, a composable function might run for every frame of a UI animation. If the function performs expensive operations, like reading from device storage, the function can cause UI jank.

你没有做错任何事情(你不是 triggering side effects 组合的一部分),所以你的代码已经很好了。