如何从这样的 react-navigation v5 函数中的帖子中获取 id?

问题描述

我正在尝试获取我过去使用 react-navigation v4 获得的帖子的 ID,如下所示:

这是我的索引屏幕

1import React,{ useContext } from 'react';
2import { View,Text,StyleSheet,FlatList,Button,TouchableOpacity } from 'react-native';
3import { Context } from '../../context/BlogContext'; 
4import { Feather } from '@expo/vector-icons';
5
6const IndexScreen = ({ navigation }) => {
7  const { state,addBlogPost,deleteBlogPost } = useContext(Context);
8  return (
9    <View style={styles.container}>
10    <Button title="Add Post" onPress={addBlogPost} />
11      <FlatList
12        data={state}
13        keyExtractor={blogPost => blogPost.title}
14        renderItem={({ item }) => {
15          return (
16            <TouchableOpacity onPress={() => navigation.navigate('Show',{ id: item.id })}>
17              <View style={styles.row}>
18                <Text style={styles.title}>{item.title} - {item.id}</Text>
19                <TouchableOpacity>
20                  <Feather style={styles.icon}
21                    name="trash"
22                    onPress={() => deleteBlogPost(item.id)}
23                  />
24                </TouchableOpacity>
25              </View>
26            </TouchableOpacity>
27          );
28        }}
29      />
30    </View>
31  );
32 }
33
34IndexScreen.navigationopitions = () => {
35  return {
36    headerRight: () => (
37      <TouchableOpacity onPress={() => navigation.navigate('Create')}>
38        <Feather name="plus" size={30} />
39      </TouchableOpacity>
40    ),41  };
42}
43
44const styles = StyleSheet.create({
45  row: {
46    flexDirection: 'row',47    justifyContent: 'space-between',48    paddingVertical: 15,49    paddingHorizontal: 10,50    borderTopWidth: 1,51    borderBottomWidth: 1,52    borderColor: 'grey'
53  },54  title: {
55    fontSize: 18,56  },57  icon: {
58    fontSize: 24,59    color: '#ff2222'
60  }
61});
62
63export default IndexScreen;
64

现在是我的显示屏幕,我曾经在其中使用 state.find (blogPost => blogPost.id === navigation.getParam('id')) 获取博客文章,如第 10 行所示。

1import { useNavigation } from '@react-navigation/native';
2import React,{ useContext } from 'react';
3import { View,StyleSheet } from 'react-native';
4import { Context } from '../../context/BlogContext';
5
6const ShowScreen = ({  navigation }) => {
7  const navigation = useNavigation();
8  const { state } = useContext(Context);
9
10    const blogPost = state.find (blogPost => blogPost.id === navigation.getParam('id'));
11
12      return (
13        <View>
14           <Text>{blogPost}</Text> 
15        </View>
16      );
17};
18
19const styles = StyleSheet.create({});
20
21export default ShowScreen;
22

现在我不再使用 react-navigation v4,而是使用 v5,但我想在第 14 行的文本行中获取 blogPost。我应该怎么做才能得到它?

解决方法

const ShowScreen = ({ route,navigation }) => {
const { state } = useContext(Context);
const {id} = route.params;

      return (
        <View>
           <Text>{id}</Text> 
        </View>
      );
};

欲了解更多信息,请查看 react navigation docs