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

问题描述 投票:0回答:1

假设我有一个结构为的本地JSON文件(./movies.json)

{ "movies": [ 
    { "title" : "Terminator", "year" :  "1984", "genre" : "Action" },
    { "title" : "Jumanji", "year" : "2017", "genre" : "Adventure"},
    { "title" : "Incredibles 2", "year" : "2017", "genre" : "Animation"}]
}

每当点击一个按钮时,我想按顺序输出一个带终止符的文本字段 - > Jumanji - > Incredibles 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>
);
}
}

我不确定如何实现按钮,以便在按下时显示下一个标题/年份/类型。帮助将不胜感激。谢谢!

javascript json reactjs mobile
1个回答
1
投票

将数组的索引存储在状态变量中。首先,我假设你把那个json传递给了state.movies

所以初始化如下:

   this.state = {
     movies: [], // where the movies are
     displayIndex: 0 // This will be the index that you show
   }

当您按下按钮时,调用一个将调用以下任一功能的功能:

moveForward(){
  this.setState({displayIndex: this.state.displayIndex++})
}
moveBack(){
  this.setState({displayIndex: this.state.displayIndex--})
}

然后,当您在渲染函数下显示字段时,抓取您需要的对象,如下所示:

render(){
   const movieData = this.state.movies[this.state.displayIndex];
   ....//Do the display logic here
© www.soinside.com 2019 - 2024. All rights reserved.