Перевести gendre_ids из TMDB API в приложение, поддерживающее реакцию - PullRequest
0 голосов
/ 05 мая 2020

Мне интересно, как показать жанр для каждого ie mov в списке. Так что у меня уже есть другие детали, такие как title, poster_path или description.

Проблема возникает, когда я пытаюсь показать жанр, потому что это числа, и я не знаю, как перевести их в строку вроде ' Horror '

Вот код для выборки данных:

    fetch(
      `https://api.themoviedb.org/3/search/movie?&api_key=${
        this.apiKey
      }&query=${searchTerm}`,
    )
      .then(data => data.json())
      .then(data => {
        const results = data.results;
        const movieRows = [];
        const movieGen = [];
        results.forEach(movie => {
          movie.poster_path =
            'https://image.tmdb.org/t/p/w500' + movie.poster_path;
          const movies = <MovieRow key={movie.id} movie={movie} />;
          movieRows.push(movies);
        });
        this.setState({rows: movieRows});
      });
  }

, а также отображать его в пользовательском компоненте, таком как mov ie card:

  viewMore = () => {
    Alert.alert(
      `PRODUCTION : ${this.props.movie.original_language}`,
      `DESCRIPTION : ${this.props.movie.overview}\n \n GENRE : ${
        this.props.movie.genre_ids
      }`,
    );
  };

  render() {
    return (
      <View
        style={{
          width: '100%',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
        <CardCustom
          title={this.props.movie.title}
          popularity={this.props.movie.popularity}
          vote_count={this.props.movie.vote_count}
          poster_path={this.props.movie.poster_path}
          onPress={this.viewMore}
        />
      </View>
    );
  }
}

export default MovieRow;

Вот как это в приложении выглядит так: application

, а ответ от api для genre_ids выглядит так enter image description here

Я заметил, что нужно использовать отдельный API для жанров. Теперь я хочу сопоставить их с текущим mov ie, и я не знаю, как это сделать.

Вот код

class MovieRow extends Component {
  constructor() {
    super();
    this.apiKey = '1bd87bc8f44f05134b3cff209a473d2e';
    this.state = {};
  }
  viewMore = () => {
    Alert.alert(
      `PRODUCTION : ${this.props.movie.original_language}`,
      `DESCRIPTION : ${this.props.movie.overview}\n \n
       GENRE : ${this.props.movie.genre_ids}`,         // < ------ NUMBER DISPLAYS. HOW TO MATCH GENRE WITH CURRENT MOVIE?
    );
    this.fetchGenre();
  };

  fetchGenre() {
    fetch(
      `https://api.themoviedb.org/3/genre/movie/list?&api_key=${this.apiKey}`,
    )
      .then(data => data.json())
      .then(data => {
        const resultGenres = data.genres;
        const genreRow = [];
        console.log(resultGenres);
        resultGenres.map(genre => {
          console.log('name', genre.name, 'id', genre.id);
          const genres = <Text>genre: {genre.name}</Text>;
          genreRow.push(genres);
        });
        this.setState({gen: genreRow});
      });
  }

  render() {
    return (
      <View
        style={{
          width: '100%',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
        <CardCustom
          title={this.props.movie.title}
          popularity={this.props.movie.popularity}
          vote_count={this.props.movie.vote_count}
          poster_path={this.props.movie.poster_path}
          onPress={this.viewMore}
        />
          {this.state.gen}
      </View>
    );
  }
}

также так выглядит ответ enter image description here

С уважением

1 Ответ

0 голосов
/ 05 мая 2020

Просто возьмите массив со всеми идентификаторами полов и сохраните его в своем состоянии, а затем, когда вы захотите отобразить его, вы просто воспользуетесь картой. вот так:

this.state.gender_ids = [
    1: "Action",
    2: "Horror",
    3: "Other gender"
]

this.props.movie.genre_ids.map(id => <Text key={this.state.gender_ids[id]}>{this.state.gender_ids[id]}</Text>)

Просто запустите следующий код в консоль вашего браузера, я почти уверен, что с этого момента вы справитесь со своей задачей.

Пример подключения:

let gendersFromServer = [
    {
        id: 28,
        name: "Action"
    },
    {
        id: 12,
        name: "Adventure"
    },
    {
        id: 16,
        name: "Animation"
    },
    // other genders here
]

let gender_ids = [] // intialize with an empty array
gendersFromServer.map(el => gender_ids[el.id] = el.name) // here you transform the data
// here you can setState({gender_ids})

const movie = {
    gender_ids: [
        28,
        12,
        16
    ]
    // rest of data
}

// how to get text gender, notice that gender_ids from console log is the one you use in state, not the one from the movie
movie.gender_ids.map(id => console.log(gender_ids[id]))

РЕДАКТИРОВАТЬ 2:

Надеюсь, это наконец решит вашу проблему

import React from 'react'
import { SafeAreaView, ScrollView, View, Text } from 'react-native'

const API_KEY = '1bd87bc8f44f05134b3cff209a473d2e'

export default props => {

    const [genres, setGenres] = React.useState([])
    const [movies, setMovies] = React.useState([])

    React.useEffect(() => {

        fetch('https://api.themoviedb.org/3/search/movie?&query=Now+You+See+Me&api_key=' + API_KEY)
        .then(res => res.json())
        .then(result => {
            setMovies(result.results)
        })

        fetch('https://api.themoviedb.org/3/genre/movie/list?&api_key=' + API_KEY)
        .then(genre => genre.json())
        .then(result => {
            const genres = result.genres.reduce((genres,gen) => {
                const { id, name } = gen
                genres[id] = name
                return genres
            },[])
            setGenres(genres)
        })

    },[])

    const Movies = () => movies.map(movie => {
        return (
            <View>
                <Text>{movie.title}</Text>
                <View>
                    <Text>Genres :</Text>
                    {
                        movie.genre_ids.map(id => {
                            return <Text>{genres[id]}</Text>
                        })
                    }
                </View>
            </View>
        )
    })

    return (
        <SafeAreaView style={{flex: 1}}>
            <ScrollView style={{flex: 1}}>
                <Text>Movies here</Text>
                <Movies />
            </ScrollView>
        </SafeAreaView>
    )
}
...