状态未在 setInterval 内更新,模态未显示本机反应

时间:2021-06-29 11:45:09

标签: javascript reactjs react-native

我正在创建一个基于位置的应用程序,当用户打开时,应用程序用户的位置被跟踪并发送到服务器。每 30 秒获取一次位置。 API 调用成功后,应显示 Modal。但是模态没有显示。状态未更新。下面是我用过的代码,

import React, {Component} from 'react';
import {Provider} from 'react-redux';
import {SafeAreaProvider} from 'react-native-safe-area-context';

import App from './App';
import configureStore from './configureStore';
import Geolocation from 'react-native-geolocation-service';
import {PermissionsAndroid, Platform} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import axios from 'axios';

export default class setup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treasurePopup: false,
      treasure_details: [],
      isLoading: false,
      store: configureStore(() => this.setState({isLoading: false})),
    };
  }

  async componentDidMount() {
    if (Platform.OS !== 'android') {
      Geolocation.requestAuthorization();
      Geolocation.setRNConfiguration({
        skipPermissionRequests: false,
        authorizationLevel: 'whenInUse',
      });
    } else {
      await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      );
    }

    setInterval(() => {
      Geolocation.getCurrentPosition(
        position => {
          console.log(position.coords);

          AsyncStorage.getItem('@deviceid:key').then(value => {
            let data = {
              lat: position.coords.latitude,
              lon: position.coords.longitude,
              userid: value,
            };

            axios({
              url: '',
              type: 'POST',
              method: 'POST',
              data,
              headers: {
                Auth: 'unauthenticated-user-no-api-token',
              },
            })
              .then(function(response) {
                if (response.data.status === 'success') {
                  this.setState({
                    treasurePopup: true,
                    treasure_details: response.data.treasure_details,
                  });
                }
              })
              .catch(function(error) {});
          });
        },
        error => {
          // See error code charts below.
          console.log(error.code, error.message);
        },
        {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
      );
    }, 30000);
  }

  renderTreasurePopup() {
    return (
      <Modal isVisible={this.state.treasurePopup} backdropOpacity={0.5}>
        <View style={styles.innerContainerDialogNew}>
          <View style={styles.messageHeaderView}>
            <Text style={styles.headerTextStyle}>Details of Treasure</Text>
            <TouchableOpacity
              onPress={() => this.setState({treasurePopup: false})}>
              <Image
                style={styles.cancelImageStyle}
                source={require('../../../img/closeicon.png')}
              />
            </TouchableOpacity>
          </View>
          <ScrollView>
            <View>
              <Text style={[styles.center, styles.centerRed]}>
                {this.state.treasure_details.treasure_title}
              </Text>
              <Text style={styles.center}>
                {this.state.treasure_details.text1} |{' '}
                {this.state.treasure_details.text2}
              </Text>
              <View style={styles.bgyellow}>
                <HTML html={this.state.treasure_details.treasure_desc} />
              </View>
            </View>
          </ScrollView>
          <TouchableOpacity
            onPress={() => this.setState({treasurePopup: false})}>
            <Text style={styles.okButtonTextStyle}> OK </Text>
          </TouchableOpacity>
        </View>
      </Modal>
    );
  }

  render() {
    return (
      <Provider store={this.state.store}>
        <SafeAreaProvider>
          <App />
          {this.state.treasurePopup && this.renderTreasurePopup()}
        </SafeAreaProvider>
      </Provider>
    );
  }
}

以上代码是否正确?

如果我在 alert() 内放置一个 if (response.data.status === 'success') {},它会显示。

成功 axios call popup 没有显示后,我认为 setInterval 内的状态没有更新。有没有办法解决这个问题。这是我的应用程序的入口文件。

我真的卡在这里了。

0 个答案:

没有答案