我有一个主屏幕,其中有一个FlatList显示图像和电影标题(包装在一个框组件),当该组件被点击时,它将被定向到电影细节屏幕.在电影细节上有相似的电影部分,这部相似的电影使用与主屏幕上相同的方式显示电影,当我按下电影推荐部分中的一部电影时,电影细节屏幕的内容不会随着我按下的电影而改变,我如何才能使当我按下相似电影部分中的一部电影时(在MovieDetail上)它会改变MovieDetail屏幕的内容?

这是我的主屏幕

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataCSoon: [],
      isContentLoading: false
      isFetching: false,
    };
  }

  getComingSoon = () => {
    fetch(
      'https://api.themoviedb.org/3/movie/upcoming?api_key=<The API Key Here>'
    )
      .then((response) => response.json())
      .then((json) =>
        this.setState({
          dataCSoon: json.results,
        })
      )
      .catch((error) => console.error(error))
      .finally(() =>
        this.setState({
          isContentLoading: false,
          isFetching: false,
        })
      );
  };

  componentDidMount = () => {
    this.getComingSoon();
  };

  renderItem = ({ item }) => {
    const { navigation } = this.props;
    return (
      <>
        <Pressable
      onPress={() =>
        navigation.navigate('Detail Film', {
          data: item.id,
          title: item.title,
        })
      }>
      <Box alignItems="center">
        <Box
          maxW="150"
          h="260"
          rounded="lg"
          overflow="hidden"
          borderWidth="1"
          borderColor="coolGray.600"
          backgroundColor="gray.700"
          shadow="2"
          m="2">
          <Box>
            <AspectRatio w="100%" ratio={16 / 9}>
              <Image
                source={{
                  uri: 'https://image.tmdb.org/t/p/w500/' + item.poster_path,
                }}
                alt="image"
                h="200"
                w="100%"
              />
            </AspectRatio>
            <Center
              backgroundColor="rgba(52, 52, 52, 0Bu.7)"
              position="absolute"
              mt="176"
              h="6"
              w="20"
              roundedTopRight="10"
              roundedBottomRight="10">
              <HStack>
                <Icon
                  size="5"
                  color="#FF8700"
                  as={<Ionicons name="star-outline" />}
                />
                <Text color="#FF8700" fontWeight="700" fontSize="14" ml="2">
                  {item.vote_average}
                </Text>
              </HStack>
            </Center>
          </Box>
          <Stack p="4" space={3} mt="110">
            <Stack space={2}>
              <Heading fontSize="15" ml="-1" noOfLine="3" color="#fff">
                {item.title}
              </Heading>
            </Stack>
          </Stack>
        </Box>
      </Box>
    </Pressable>
      </>
    );
  };

  render() {
    const {
      dataCSoon
    } = this.state;
    const { navigation } = this.props;
    return (
      <ScrollView>
        <Box bgColor="#242A32" h="100%" pl="5" mb="5">
          <Text color="#FFFFFF" mt="10" fontWeight="bold" fontSize="20">
            Welcome
          </Text>
          <Text color="#FFFFFF" fontWeight="semibold" fontSize="15">
            Choose Movie To View
          </Text>

          <View justifyContent="center">
            <HStack my="4" space={145} w="100%" mt="5">
              <Text color="#ffffff" fontSize="18">
                Coming Soon
              </Text>
              <Pressable
                onPress={() =>
                  navigation.navigate('More', { data: dataCSoon })
                }>
                <Text color="#0296E5" fontSize="15" mr="8" fontWeight="bold">
                  See More
                </Text>
              </Pressable>
            </HStack>
            <FlatList
              mt="-2"
              horizontal
              data={ dataCSoon.slice(0, 4)}
              keyExtractor={(item) => item.id}
              renderItem={this.renderItem}
              onRefresh={() => this.onRefresh()}
              refreshing={this.state.isFetching}
            />
          </View>
        </Box>
      </ScrollView>
    );
  }
}

export default Home;

这是电影详细信息屏幕

class MovieDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataId: this.props.route.params.data,
      content: [],
      contentGenre: [],
      similar: [],
      isContentLoading: true,
    };
  }

  getContent = (movie_id) => {
    fetch(
      `https://api.themoviedb.org/3/movie/${movie_id}?api_key=<The API Key>`
    )
      .then((response) => response.json())
      .then((json) =>
        this.setState({
          content: json,
        })
      )
      .catch((error) => console.error(error))
      .finally(() =>
        this.setState({
          isContentLoading: false,
          isFetching: false,
        })
      );
  };

  getDetails = (movie_id) => {
    fetch(
      `https://api.themoviedb.org/3/movie/${movie_id}?api_key=<The API Key>`
    )
      .then((response) => response.json())
      .then((json) =>
        this.setState({
          contentGenre: json.genres[0].name,
          activeContent: json.id,
        })
      )
      .then(() => this.fetchContent(this.state.activeContent))
      .catch((error) => console.error(error))
      .finally(() =>
        this.setState({
          isCategoriesLoading: false,
        })
      );
  };


  getSimilar = (movie_id) => {
    fetch(
      `https://api.themoviedb.org/3/movie/${movie_id}/similar?api_key=<The API Key>`
    )
      .then((response) => response.json())
      .then((json) => this.setState({ similar: json.results }))
      .catch((error) => console.error(error))
      .finally(() =>
        this.setState({
          isContentLoading: false,
          isFetching: false,
        })
      );
  };

  componentDidMount = () => {
    const { dataId } = this.state;
    this.getContent(dataId);
    this.getDetails(dataId);
    this.getSimilar(dataId);
  };

  renderItem = ({ item }) => {
    const { navigation } = this.props;
    return (
      <>
        <Pressable
          onPress={() =>
            navigation.navigate('Detail Film', {
              data: item.id,
              title: item.title,
            })
          }>
          <Box alignItems="center">
            <Box
              maxW="150"
              h="260"
              rounded="lg"
              overflow="hidden"
              borderWidth="1"
              borderColor="coolGray.600"
              backgroundColor="gray.700"
              shadow="2"
              m="2">
              <Box>
                <AspectRatio w="100%" ratio={16 / 9}>
                  <Image
                    source={{
                      uri:
                        'https://image.tmdb.org/t/p/w500/' + item.poster_path,
                    }}
                    alt="image"
                    h="200"
                    w="100%"
                  />
                </AspectRatio>
                <Center
                  backgroundColor="rgba(52, 52, 52, 0.7)"
                  position="absolute"
                  mt="176"
                  h="6"
                  w="20"
                  roundedTopRight="10"
                  roundedBottomRight="10">
                  <HStack>
                    <Icon
                      size="5"
                      color="#FF8700"
                      as={<Ionicons name="star-outline" />}
                    />
                    <Text color="#FF8700" fontWeight="700" fontSize="14" ml="2">
                      {item.vote_average.toFixed(1)}
                    </Text>
                  </HStack>
                </Center>
              </Box>
              <Stack p="4" space={3} mt="110">
                <Stack space={2}>
                  <Heading fontSize="15" ml="-1" noOfLine="3" color="#fff">
                    {item.title}
                  </Heading>
                </Stack>
              </Stack>
            </Box>
          </Box>
        </Pressable>
      </>
    );
  };

  render() {
    const {
      contentGenre,
      content,
      isContentLoading
      similar,
    } = this.state;
    return isContentLoading ? (
      <Spinner color="indigo.500" size="lg" mt="100%" />
    ) : (
      <ScrollView h="100%">
        <Box bgColor="#242A32" h="100%" pb="50">
          <Image
            source={{
              uri: 'https://image.tmdb.org/t/p/w500/' + content.backdrop_path,
            }}
            w="100%"
            h="250"
            resizeMode="contain"
            opacity="0.6"
            borderBottomLeftRadius="20"
            borderBottomRightRadius="20"
          />
          <Image
            source={{
              uri: 'https://image.tmdb.org/t/p/w500/' + content.poster_path,
            }}
            w="30%"
            h="150"
            ml="5"
            mt="-25%"
            resizeMode="contain"
            rounded="25"
          />

          <View flexDirection="column" ml="4" mr="4">
            <Text
              color="#ffffff"
              fontSize="18"
              fontWeight="bold"
              ml="38%"
              mt="-17%"
              w="60%"
              noOfLine="2">
              {content.title}
            </Text>
            <HStack mt="10" justifyContent="center">
              <Text color="#ffffff" fontSize="14">
                {content.id}
              </Text>
              <Divider
                bg="#3A3F47"
                thickness="3"
                mx="2"
                orientation="vertical"
              />

              <Text color="#fff" fontSize="16" mt="4">
                Similar
              </Text>
              <Divider
                bg="#3A3F4F"
                thickness="3"
                w="20%"
                orientation="horizontal"
              />
              <FlatList
                mt="2"
                horizontal
                data={similar}
                keyExtractor={(item) => item.id}
                renderItem={this.renderItem}
              />
            </VStack>
          </View>
        </Box>
      </ScrollView>
    );
  }
}

export default MovieDetail;

在Home Screen和MovieDetail屏幕上有一个renderItem函数来显示电影细节,当按下这两个按钮时都会进入MovieDetail屏幕.

推荐答案

MovieDetail屏幕中,您不需要导航,因为您不想更改当前屏幕. 要保持相同的逻辑并更新导航参数,请替换

navigation.navigate('Detail Film', {
  data: item.id,
  title: item.title,
})

使用

navigation.setParams({
  data: item.id,
  title: item.title,
})

Be aware that you will need to update the data. I think you may need to add a componentDidUpdate function to do so. I'm no longer familiar 使用 it now, as I would do it in a functional way 使用 useEffect.

React-native相关问答推荐

react 本机中的TextInput对齐中的长文本

Firebase身份验证Redux使用说明

如何将S的此API输出输出到平面列表中?控制台将数据及其可视记录到平面列表中,但我无法输出到平面列表中

React Native 中的视图与 Flex 不占用相同的高度空间

react 本机 TextInput 将其他元素移出屏幕

有人可以帮我实现 Font.loadAsync

React Native StackNavigator 初始路由名称

带有 SafeAreaView-wrapper 的 react-native Modal 不起作用

React-Native 按钮居中对齐

未找到 xcode 'boost/config/user.hpp' 文件

可以在没有 await 关键字的情况下调用异步函数吗?

React Native with Typescript and Jest 在 0.57 更新后被 destruct :Couldn't find preset "module:metro-react-native-babel-preset" relative to directory

无法加载 exp:// 出了点问题

在 react-native 和 firebase 3.1 中登录 Facebook

如何在我的 React Native Android 应用程序中显示当前的 CodePush 版本标签?

React Navigation 中的选项卡导航器图标

如何用 Realm 元素文件组织 React Native?

React Native 中的 CSS 三角形

移动应用程序不需要 CORS?

使用行数react-native文本组件