[英]Pass function from one screen to another in react native
Im trying to pass a function handleNewFavourite
(which updates my favouriteList
state array) from my HomeScreen
to my DetailsScreen
via navigation params but Im getting the following error: Non-serializable values were found in the navigation state
我试图通过导航参数将函数handleNewFavourite
(它更新我的favouriteList
状态数组)从我的HomeScreen
传递到我的DetailsScreen
creen 但我收到以下错误: Non-serializable values were found in the navigation state
How should I pass functions that modified the state between different stack screens?我应该如何传递修改不同堆栈屏幕之间状态的函数?
HomeScreen code:主屏幕代码:
<FlatList data={checkCategory()} renderItem={({item}) => ( <TouchableOpacity onPress={() => navigation.navigate('Details', { item, handleNewFavourite, }) }> <LessonCard lesson={item} /> </TouchableOpacity> )} />
DetailScreen code:详细屏幕代码:
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;
For situation like this, you should learn global state management.对于这种情况,你应该学习全局状态管理。 ( Context API - Redux etc. ) (上下文 API - Redux 等)
I think you are disrupting in the wrong way the parameters passed to DetailScreen
it should be something like this:我认为您以错误的方式破坏了传递给DetailScreen
的参数,它应该是这样的:
const LessonDetails = ({route}: LessonProps) => {
const {lesson, handleNewFavourite} = route.params;
// The rest of your component here
}
As the documentation here suggested.正如此处的文档所建议的那样。 But as @omerfarukose mentioned is not a bad idea to use state management in this particular scenario但是正如@omerfarukose 提到的那样,在这种特定情况下使用状态管理并不是一个坏主意
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.