【问题标题】:Translate gendre_ids from TMDB API in react-native application在 react-native 应用程序中从 TMDB API 翻译 gendre_ids
【发布时间】:2020-05-05 14:33:07
【问题描述】:

我想知道如何为列表中的每部电影显示类型。所以我已经有了其他详细信息,例如标题、poster_path 或描述。

当我试图展示一个流派时,问题就来了,因为它们是一个数字,我不知道如何将它们翻译成像“恐怖”这样的字符串

这里是获取数据的代码:

    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});
      });
  }

也可以在自定义组件中显示,比如电影卡:

  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;

这是在应用程序中的样子:

api 对genre_ids 的响应看起来像这样

我注意到我必须为流派使用单独的 API。现在我想将它们与当前电影相匹配,但我不知道该怎么做。

这是一个代码

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>
    );
  }
}

这也是响应的样子

问候

【问题讨论】:

    标签: javascript arrays react-native fetch


    【解决方案1】:

    只需获取一个包含所有性别 ID 的数组并将其存储到您的状态中,然后当您想要显示它时,您只需使用地图即可。像这样:

    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>
        )
    }
    

    【讨论】:

    • 好吧,在这种情况下我得到了“对象对象”:(
    • 好吧,检查tmdb接收到的id的格式,并解析它是一个id为对的数组:性别,一切都会好的。或者发布一个ids格式的例子,我也很乐意帮助解析,我没有tmdb api key,所以我不知道格式。
    • 好吧,我想通了。要获得正确的流派名称,我需要使用另一个 api 链接。现在,当我有类型时,我不知道如何将它们与当前电影匹配
    • 添加您获取的性别数据示例。
    • 不是真的 :( 我已经获取了流派,但是如何在“this.props.movi​​e.genre_ids”上显示它们?
    猜你喜欢
    • 2018-08-31
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多