在react native中将函数从一个屏幕传递到另一个屏幕



我试图通过导航参数从我的HomeScreen传递一个函数handleNewFavourite(更新我的favouriteList状态数组)到我的DetailsScreen,但我得到以下错误:Non-serializable values were found in the navigation state

我应该如何传递修改不同堆栈屏幕之间状态的函数?

桌面的代码:

<FlatList
data={checkCategory()}
renderItem={({item}) => (
<TouchableOpacity
onPress={() =>
navigation.navigate('Details', {
item,
handleNewFavourite,
})
}>
<LessonCard lesson={item} />
</TouchableOpacity>
)}
/>

DetailScreen代码:

const LessonDetails = ({lesson, handleNewFavourite}: LessonProps) => {
const [favourite, setFavourite] = useState<boolean>(lesson.favourite);
return (
<LessonDetailsContainer>
<LessonDetailsInfoContainer>
<LessonDetailsCategoryHead>
<LessonDetailsCategory>{lesson.category}</LessonDetailsCategory>
<TouchableOpacity
onPress={() => {
setFavourite(!favourite);
handleNewFavourite(lesson);
}}>
<LessonDetailsFavouriteIcon>
{favourite ? '❤️' : '🤍'}
</LessonDetailsFavouriteIcon>
</TouchableOpacity>
</LessonDetailsCategoryHead>
<LessonDetailsTitle>{lesson.title}</LessonDetailsTitle>
<LessonDetailsAuthor>{lesson?.author}</LessonDetailsAuthor>
</LessonDetailsInfoContainer>
<LessonDetailsCardImage
source={{
uri: lesson.image,
}}
/>
<LessonDetailsContentContainer>
<LessonDetailsDescriptionText>
{lesson.content}
</LessonDetailsDescriptionText>
</LessonDetailsContentContainer>
</LessonDetailsContainer>
);
};
export default LessonDetails;

对于这种情况,您应该学习全局状态管理。(上下文API - Redux等)

我认为你以错误的方式扰乱了传递给DetailScreen的参数,它应该是这样的:

const LessonDetails = ({route}: LessonProps) => {
const {lesson, handleNewFavourite} = route.params;
// The rest of your component here
}

正如这里的文档所建议的。但是正如@omerfarukose所提到的,在这个特定的场景中使用状态管理并不是一个坏主意

相关内容

  • 没有找到相关文章

最新更新