Javascript (React Native)按下按钮时检索JSON文件中的下一个值

Javascript (React Native)按下按钮时检索JSON文件中的下一个值,javascript,json,reactjs,mobile,Javascript,Json,Reactjs,Mobile,假设我有一个本地JSON文件./movies.JSON,其结构如下 { "movies": [ { "title" : "Terminator", "year" : "1984", "genre" : "Action" }, { "title" : "Jumanji", "year" : "2017", "genre" : "Adventure"},  { "title" : "Incredibles 2", "year" : "2017", "genre" : "An

假设我有一个本地JSON文件./movies.JSON,其结构如下

{ "movies": [ 
    { "title" : "Terminator", "year" :  "1984", "genre" : "Action" },
    { "title" : "Jumanji", "year" : "2017", "genre" : "Adventure"},
    { "title" : "Incredibles 2", "year" : "2017", "genre" : "Animation"}]
}
无论何时单击按钮,我都希望输出一个文本字段,例如 终结者->朱曼基->不可思议2,按顺序。 我还想能够访问所有三个标题,电影,流派在单独的文本字段顺序,当按钮被点击

这就是我到目前为止所做的,只是为了得到电影的标题。这不起作用,因为我认为我没有正确地从JSON文件中提取

import jsonData from "./movies.json";

export default class Movies extends React.Component {
  constructor(props) {
  super(props);
      this.state = {
         results:{
         titles: [],
         years: [], 
         genres: []
       }
     }
  };
}
componentDidMount = () => {
  // const data = json.stringify(jsonData)  I think this line is not correct 
  this.setState({ data })
}
render () { 
  titles_list = this.state.results.titles.map((item) => {
  return (
      <View key={item.title}>
        <Text>
          {item.title}
        </Text>
      </View>
    );
 });
return (
  <View>
    {titles_list}
  </View>
);
}
}

我不知道如何实现一个按钮,这样当按下它时,下一个标题/年份/流派就会显示出来。我们将不胜感激。谢谢

将数组的索引存储在状态变量中。 首先,我假设您将json传递到state.movies中

因此,按如下方式初始化它:

   this.state = {
     movies: [], // where the movies are
     displayIndex: 0 // This will be the index that you show
   }
render(){
   const movieData = this.state.movies[this.state.displayIndex];
   ....//Do the display logic here
按下按钮时,调用将调用以下任一函数的函数:

moveForward(){
  this.setState({displayIndex: this.state.displayIndex++})
}
moveBack(){
  this.setState({displayIndex: this.state.displayIndex--})
}
然后,当显示渲染函数下的字段时,按如下方式抓取所需的对象:

   this.state = {
     movies: [], // where the movies are
     displayIndex: 0 // This will be the index that you show
   }
render(){
   const movieData = this.state.movies[this.state.displayIndex];
   ....//Do the display logic here

谢谢我现在遇到的唯一问题是,我不确定如何提取电影JSON本地文件,并在列表中设置标题、类型和年份,如电影:[]您创建的电影。你能解释一下这一部分吗?你需要一些东西来承载json,或者简单地在js中硬编码json。如果它是托管的,你将需要像拉它的东西。如果是硬编码的,只需让组件加载.setState或传递到组件的props中,后者更符合react wayimport jsonData from./data.json;componentDidMount==>{this.setState{jsonData}}-这是正确的方法吗?