簡體   English   中英

在響應本機中按時間限制迭代JSON數據

[英]Iterate JSON Data by some time limit in react native

目前我在react-native<View>內部有一個<Text>值。 而且我必須傳遞一個JSON來遍歷該文本字段。 所以我希望它們是,假設JSON包含4個對象,因此最初,文本字段將在<View>顯示第一個對象的值。 5秒后,我必須顯示第二個對象,而不是第一個對象。 就像明智的做法一樣,它必須持續到最后一個對象到來為止。 例如 ,

  const mydata = [ { name:"Aaa" //object 1 }, { name:"Bbb" //object 2 }, { name:"Ccc" //object 3 }, { name:"Ddd" //object 5 }, ] //initial view <View> <Text>{object1.name} </Text> /// ---> Aaa </View> //After 5 seconds <View> <Text>{object2.name} </Text> /// ---> Bbb </View> //Like this it has to go on . 

並且需要每5秒鍾自動更改一次。在此附上我的代碼,

 <View> {allData.map((data,i) => ( <DataInDetail // this is the component i imported name={data.name} /> ))} </View> //DataInDetail component import React, { Component } from "react"; import { View, Text, Image, StyleSheet, Dimensions, Platform } from "react-native"; const win = Dimensions.get("window"); const width = win.width; export default class DataInDetail extends Component { render() { return ( <View> <Text>{this.props.name}</Text> </View> ); } } 

現在只顯示最后一個JSON。 請有人從這澄清我。 提前致謝 。

您可以使用setTimeout實現此目的。 檢查TimerMixin以使用this.setTimeout 卸載組件后,TimerMixin可幫助您解決狀態設置錯誤。

const data = [ { name:"Aaa" }, { name:"Bbb" }, { name:"Ccc" }, { name:"Ddd" } ];
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ''
    };
  }

  componentDidMount() {
    data.forEach((d, index) => {
      this.setTimeout(() => {
        this.setSTate({ name: d.name });
      }, (5000 * index))
    })
  }

  render() {
    return(
      <View>
        <DataInDetail name={this.state.name} />
      </View>
    )
  }
}

UPDATE (使它無限期地循環)您可以將setTimeout循環轉換為一個函數,並可以在循環的最后一個索引處調用它。 我們將index增加1,因為我們希望在初次啟動后5秒后發生更改。

const data = [ { name:"Aaa" }, { name:"Bbb" }, { name:"Ccc" }, { name:"Ddd" } ];
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ''
    };
  }

  setLoop(isIntial) {
    data.forEach((d, index) => {
      setTimeout(() => {
        this.setSTate({ name: d.name }, () => {
          if (index == (data.length - 1)) this.setLoop.bind(this, false);
        });
      }, (isInitial === true ? (5000 * index) : (5000 * (index + 1) )));
    });
  }

  componentDidMount() {
    this.setLoop(true);
  }

  render() {
    return(
      <View>
        <DataInDetail name={this.state.name} />
      </View>
    )
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM