React Native:每按一次按钮

时间:2017-08-11 08:12:56

标签: react-native

我几天前刚刚开始使用React Native,我发现自己有点陷入困境。我想通过单击按钮从api逐个显示值。但是,如何在不每次获取数据的情况下执行此操作,而是每10次点击一次?我现在拥有的代码并没有按照我想要的方式工作,而且我明白为什么 - countData()函数总是被重新调用,因此变量i始终保持为零并且永远不会前进。理想情况下,我想循环遍历第一组值,在单击按钮时逐个显示它们,然后在用完值后获取新数据(来自相同的api)。

export default class ComponentOne extends Component {

 constructor(props) {
 super(props);
 this.state = {
   questions: '',
   questions2: '',
 }
}


fetchData() {
  if (this.state.questions == '') {
   fetch('my url')
    .then((response) => response.json())
    .then((responseData) => {
        this.setState({
            questions: responseData,
        });
    this.countData();
   })
    .done();
  }
  else this.countData();
 }

countData() {
  for (let i=0; i < this.state.questions.length; i++) {
   this.setState({
    questions2: this.state.questions[i],
  });
 }
}

render() {
 return (
  <View style={styles.container}>

     <View style={styles.textStyle}>

     <Text style={styles.instructions}>
       Welcome! Click the button to generate a question.
     </Text>

     <TouchableHighlight
     onPress={() => this.fetchData()}
     style={styles.bigButton}
     underlayColor="lightskyblue">

       <Text style={styles.bigButtonText}>Hit me</Text>

     </TouchableHighlight>

     <Text style={styles.question}>{this.state.questions2}</Text>
     </View>
  </View>
  );
 }
}

我希望问题很清楚,提前谢谢!

1 个答案:

答案 0 :(得分:1)

首先要做的事情是:你应该考虑不给你那样的api url。

我没有在应用中测试代码,但它应该可以正常工作

export default class ComponentOne extends Component {
 constructor(props) {
   super(props);
   this.state = {
     questions: [],
     question: "",
     count: 0,
   }
}

componentWillMount() {
  this.fetchData();
}

fetchData() {
  fetch('YOUR_URL')
  .then((response) => response.JSON())
  .then((responseJSON) => {
    this.setState({questions: responseJSON, count: 0})
  })
}

newQuestion() {
  if (this.state.questions[count] != null) {
    this.setState({
      question: this.state.questions[this.state.count],
      count: this.state.count + 1,
    })
  }
  else { //make the fetch call once all of your questions has been displayed
    this.fetchData();
  }  
}

render() {
 return (
  <View style={styles.container}>
     <TouchableHighlight onPress={() => this.newQuestion()}>
      <Text>Hit me</Text>
     </TouchableHighlight>

     <Text>{this.state.question}</Text>
     </View>
  </View>
  );
 }
}