简体   繁体   English

setState 在发布模式下无法正常工作 React Native iOS

[英]setState not working properly in release mode React native iOS

I'm fetching some data from a server to load it to my app, my app doesn't load until the app loads all the data, it works perfectly in the debug mode, but when I have to test it on release mode, I have to reload it in order to make it work, and that is not the idea.我正在从服务器获取一些数据以将其加载到我的应用程序中,我的应用程序在应用程序加载所有数据之前不会加载,它在调试模式下运行良好,但是当我必须在发布模式下对其进行测试时,我必须重新加载它才能使其工作,这不是我们的想法。 Here's my code:这是我的代码:

import React, { Component } from 'react';
import { Alert, NetInfo, View, Text, AsyncStorage, TouchableWithoutFeedback, Linking, Platform } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Router from './Router';
import OnBoarding from './components/OnBoarding';
import Loading from './components/Loading';
import OneSignal from 'react-native-onesignal';
import axios from 'axios';
var DeviceInfo = require('react-native-device-info');

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
          usage: '',
          categories_hum: [],
          videoshum: [],
          categories_nov: [],
          novedades: [],
          tiendas: [],
          promociones: [],
          listadoCodigos: [],
          token: "",
          listadoCodigosRecibido: true,
          terminos: '',
          notFirst: false
        };
        this.changeUsage = this.changeUsage.bind(this);
      }

    onIds(device) {
      AsyncStorage.setItem('playerId', device.userId);
    }

    onOpened(openResult) {
     if(openResult.notification.payload.additionalData != undefined) {
      var opc = openResult.notification.payload.additionalData.opc;
      if(opc == 2) {
        opc = "2";
        AsyncStorage.setItem('opcion', opc);
      } else if(opc == 1) {
        opc = "1";
        AsyncStorage.setItem('opcion', opc);
      }
     }
    }


    componentWillMount() {
      OneSignal.addEventListener('ids', this.onIds);
      OneSignal.addEventListener('opened', this.onOpened);
    }

    componentDidMount() {
      NetInfo.isConnected.fetch().then(isConnected => {
           if(!isConnected) {
             Alert.alert (
               'No hay conexion',
               'No hay conexion a internet, debe poseer una conexion WiFi o celular para usar FerretotalApp'
             );
           }
        });

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/categoria-hum?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ categories_hum: response})
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/videoshum?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ videoshum: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/tienda_acf?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ tiendas: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/categorianovedades?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ categories_nov: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/ferretotalnovedades?per_page=100')
        .then(response => response.json())
        .then(
            response => this.setState({ novedades: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/promociones_activas?hola=1')
        .then(response => response.json())
        .then(
            response => this.setState({ promociones: response })
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/listado_codigos_usuario?deviceID="'+DeviceInfo.getUniqueID()+'"')
        .then(response => response.json())
        .then(
          response => this.setState({ listadoCodigos: response, listadoCodigosRecibido: true})
        );

        fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/terminos_condiciones?hola=1')
        .then(response => response.json())
        .then(
          response => this.setState({ terminos: response})
        );

        AsyncStorage.getItem('usage').then((result) => {
               if(!result){
                 this.setState({usage: "firstTime"});
               }else{
                 this.setState({usage: result});
               }
               //al colocar esto hara q salga siempre el onboarding
               //AsyncStorage.removeItem("usage");
             });

             AsyncStorage.getItem('notFirst').then((result) => {
               if(!result){
                 this.setState({notFirst: false});
                } else {
                   this.setState({notFirst: false})
                  }
               });

              AsyncStorage.getItem('token').then((value) => {
               if(!value){
                 var DeviceID = DeviceInfo.getUniqueID();
                 fetch('https://ferrretotalcom.kinsta.com/wp-json/wp/v2/recibir_token?deviceID="'+DeviceID+'"')
                 .then((response) => response.json())
                 .then((response) => {
                   if(response[0]){
                     AsyncStorage.setItem('token',response[0].access_token);
                     this.setState({token: response[0].access_token});
                   }
                 })
               } else {
                 this.setState({token: value})}
             });
             AsyncStorage.setItem('newCode',"false");
    }

    componentWillUnmount() {
      OneSignal.removeEventListener('ids', this.onIds);
      OneSignal.removeEventListener('opened', this.onOpened);
    }

    changeUsage(e) {
      this.setState({usage: "notFirst"});
      this.setState({notFirst: true});
    }

    render(){
      /*alert(this.state.categories_hum.length + " " + this.state.videoshum.length + " " + this.state.promociones.length
      + " " + this.state.novedades.length + " " + this.state.categories_nov.length + " " + this.state.tiendas.length + " " + this.state.listadoCodigosRecibido + " " + this.state.terminos.length) */

          if(this.state.categories_hum.length && this.state.videoshum.length && this.state.promociones.length
          && this.state.novedades.length && this.state.categories_nov.length && this.state.tiendas.length && this.state.listadoCodigosRecibido && this.state.terminos.length) {
             if(this.state.usage.length && this.state.usage == "firstTime"){
               //al colocar esto solo saldra el onboarding la primera vez
               AsyncStorage.setItem('usage', "notFirst");
               AsyncStorage.setItem('notFirst', true)
               //al colocar esto, guardara la fecha de instalacion de la aplicacion (realmente la primera vez que se mete)

                AsyncStorage.getItem('installed').then((result) => {
                if(!result) {
                  var date = new Date();
                  date = date.toString();
                  AsyncStorage.setItem('installed', date);
                }
              });

               return (
                  <OnBoarding changeUsage={this.changeUsage} terminos={this.state.terminos}/>
               );
             } else if(this.state.usage == "notFirst" && this.state.notFirst == false) {
               return(
                <OnBoarding changeUsage={this.changeUsage} terminos={this.state.terminos} notFirst={true}/>
               );
            } else if(this.state.usage == "notFirst" && this.state.notFirst) {
                    return (
                    <View style={{flex:1}}>
                        <Router
                            categories_hum={this.state.categories_hum}
                            videoshum={this.state.videoshum}
                            categories_nov={this.state.categories_nov}
                            novedades={this.state.novedades}
                            tiendas={this.state.tiendas}
                            listadoCodigos={this.state.listadoCodigos}
                            promociones={this.state.promociones}
                            token={this.state.token}
                            terminos={this.state.terminos}
                        />
                    </View>
                );
              }
          } else{
            return (
                <Loading/>
            )
        }
    }
}

export default App;

As you can see, I'm fetching all the data I need in the "ComponentDidMount" method, then I store the JSON data in multiple states and pass it to the screens I need, the thing is that in release mode, the states don't have anything after it "loads" and it only happens the first time you open the app and only in release mode, I check the response from fetch and it is ok, it brings the data.如您所见,我正在“ComponentDidMount”方法中获取我需要的所有数据,然后我将 JSON 数据存储在多个状态中并将其传递给我需要的屏幕,问题是在发布模式下,状态不“加载”后没有任何内容,并且仅在您第一次打开应用程序时发生并且仅在发布模式下发生,我检查了 fetch 的响应,没关系,它带来了数据。 I have tried lot of things but I can't still figured out what it is since it works well in debug mode.我尝试了很多东西,但我仍然无法弄清楚它是什么,因为它在调试模式下运行良好。 Please if you have any ideas, you can tell me.如果您有任何想法,请告诉我。

were you able to solve this issue?? 您能解决这个问题吗? i'm facing same issue. 我面临着同样的问题。 your help would be really appreciated. 您的帮助将不胜感激。

From the description , it seems the task is not being synchronous with expected behavior.从描述来看,该任务似乎与预期行为不同步。 setState is asynchronous by default but in my experience I have known some cases where I have to make it explicitly asynchronous using "Async" and "await". setState 默认情况下是异步的,但根据我的经验,我知道在某些情况下我必须使用“Async”和“await”使其显式异步。 I am not sure but It might be a work around for you too in every setState invoking methods as belows:我不确定,但在每个 setState 调用方法中,这对您来说也可能是一种解决方法,如下所示:

  async changeUsage(e) {
  await this.setState({usage: "notFirst"});
  await this.setState({notFirst: true});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM