Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在呈现之前获取数据[本机反应]_Javascript_Reactjs_React Native - Fatal编程技术网

Javascript 在呈现之前获取数据[本机反应]

Javascript 在呈现之前获取数据[本机反应],javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在制作一个可以读取特定二维码的应用程序 但是我有一个问题,我的getJSON(它调用我的webservice)函数在代码的其余部分之后自动启动,我无法使用它提供的内容 你知道为什么会这样,以及如何解决这个问题吗 谢谢 我的git: //这是导航器的示例代码// 从“React”导入React,{Component}; //在我们的代码中导入react。 从“react native”导入{样式表、视图、文本、平面列表、警报}; 从“反应本机手势处理程序”导入{TextInput}; 从“@r

我正在制作一个可以读取特定二维码的应用程序

但是我有一个问题,我的getJSON(它调用我的webservice)函数在代码的其余部分之后自动启动,我无法使用它提供的内容

你知道为什么会这样,以及如何解决这个问题吗

谢谢

我的git:

//这是导航器的示例代码//
从“React”导入React,{Component};
//在我们的代码中导入react。
从“react native”导入{样式表、视图、文本、平面列表、警报};
从“反应本机手势处理程序”导入{TextInput};
从“@react native community/async storage”导入异步存储;
从“react native elements”导入{Button,ThemeProvider,Overlay};
从“反应本机矢量图标/FontAwesome”导入图标;
让数据;
让html=[]
让getJSON=函数(url,回调){
var xhr=new XMLHttpRequest();
xhr.open('GET',url,true);
xhr.responseType='json';
xhr.onload=函数(){
var status=xhr.status;
如果(状态===200){
回调(null,xhr.response);
}否则{
回调(状态,xhr.response);
}
};
xhr.send();
};
常量getAllData=()=>{
AsyncStorage.getAllKeys().then((键)=>{
返回AsyncStorage.multiGet(键)
。然后((结果)=>{
数据=结果;
datas.sort().reverse()
setHtml()
}).catch((e)=>{
});
});
}
//AsyncStorage.clear();
getAllData()
常量setHtml=()=>{
html=[]
如果(数据!=未定义){
对于(变量i=0;iif(html.length),因为您正在严重滥用React。整个想法是您使用状态和道具来控制它(=您的页面/组件)何时应该“重新呈现”,但您正在使用变量将信息保存在react组件生命周期之外,因此无法利用这一点。请在
componentDidMount
内执行api调用,使用
setState
将结果保存在您的状态中,并从
render
函数内的状态获取数据。
//This is an example code for Navigator// 
import React, { Component } from 'react';

//import react in our code. 
import { StyleSheet, View, Text, FlatList, Alert} from 'react-native';
import { TextInput } from 'react-native-gesture-handler';
import AsyncStorage from '@react-native-community/async-storage';
import { Button, ThemeProvider, Overlay } from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';


let datas;
let html = []

let getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
      callback(null, xhr.response);
    } else {
      callback(status, xhr.response);
    }
  };
  xhr.send();
};

const getAllData = () =>{
  AsyncStorage.getAllKeys().then((keys) => {
    return AsyncStorage.multiGet(keys)
      .then((result) => {
        datas = result;
        datas.sort().reverse()
        setHtml()
      }).catch((e) =>{
      });
  });
}
//AsyncStorage.clear();
getAllData()

const setHtml = () => {
  html = []
  if (datas != undefined) {
    for (var i=0; i < datas.length; i++) {
      if (html.length <= i) {

        getJSON('http://elarnes.fr/get_qrcode.php?idQrCode=' + JSON.stringify(datas[i][1]).replace(/['"]+/g, '').split(';')[1],
        (err, data) => {
            if (err !== null) {
                console.log('Something went wrong: ' + err);
            } else {
                console.log(datas);
               // console.log(data[0]["code"]);
            }
          }
        );
        console.log(datas[i][0]);

        html.push(
          {key: datas[i][0], value: datas[i][1]},
        )
      }
    }
  }
}



export default class Historique extends Component {
  state = {
    uniqueValue: 1
  }
  forceRemount = () => {
    this.setState(({ uniqueValue }) => ({
      uniqueValue: uniqueValue + 1
    }));
  }
  static navigationOptions = {
    title: 'Historique',
    headerBackTitle: 'Retour',
    headerStyle: {
      backgroundColor: '#557aca',
      borderBottomColor: 'gainsboro',

      //Sets Header color
    },
    headerTintColor: '#fff',
    //Sets Header text color
    headerTitleStyle: {
      fontWeight: 'bold',
      //Sets Header text style
  },
    //Sets Header text of Status Bar
  };

  render() {

    getAllData()

    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
        <FlatList
          data={html}
          renderItem={
            ({item}) => 
              <View style={styles.item}><Text style={styles.itemText}>{item.value}</Text>
                <ThemeProvider>
                  <Button style={styles.button}
                    title="Visualiser"
                    titleStyle={{fontSize: 15}}
                    onPress={() => navigate('Informations', {
                      itemValue: item.value
                    })}
                  />
                </ThemeProvider>
              </View>
          }
        />
      <Button
      title="Actualiser"
      titleStyle={{fontSize: 15}}
      onPress={this.forceRemount} />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  item: {
    borderBottomWidth: 1,
    borderBottomColor: 'gainsboro',
    backgroundColor: 'whitesmoke'
  },
  itemText: {
    padding: 10,
    fontSize: 15,
    textAlign: "center"
  },
  show: {
    textAlign: "right"
  },
  button: {
    marginBottom: 10,
    alignItems: "center",
    fontSize: 15,
  }
});

/*
                  <Button style={styles.button}
                    title="Visualiser"
                    titleStyle={{fontSize: 15}}
                    onPress={() => Alert.alert("Info",item.value)}
                  />
*/