Реагирующее собственное хранилище MobX не определено / не передано провайдеру только в сборке выпуска

У меня возникла эта проблема с реакцией native и mobx/mobx-реагировать на то, что при сборке в режиме разработки все работает отлично, но при попытке в режиме релиза все, что связано с хранилищем, не определено.

Буду признателен за любой вклад! Спасибо

Вот установленные версии, я попытался также обновить / понизить:

├── babel-plugin-transform-class-properties@6.24.1
├── babel-plugin-transform-decorators-legacy@1.3.5
├── babel-preset-react-native-stage-0@1.0.1
├── mobx@3.6.2
├── mobx-react@4.4.3
├── react@16.3.1
├── UNMET PEER DEPENDENCY react-native@0.55.4

Store.js

import { observable, extras } from 'mobx';

extras.isolateGlobalState();

class ObservableStore {

  @observable user = {
    phone_number: "12345678"
  };

  @observable mediaList = [];

  updateUser (item) {
    this.user = item;
  }

  clearUser () {
    this.user = {
      phone_number: ""
    };
  }

}


const observableStore = new ObservableStore();
export default observableStore;

MediaList.js

import React from 'react';
import { Text, View, Alert, FlatList, Image, ImageBackground, TouchableHighlight, RefreshControl, PermissionsAndroid } from 'react-native';
import Swipeable from 'react-native-swipeable-row';
import * as mobx from 'mobx';
import { observer, inject } from 'mobx-react/native';
import styles from './styles';
import path from 'react-native-path';
import fs from 'react-native-fs';
import { Actions } from 'react-native-router-flux';

import FtpService from '../../Services/FtpService';
import randomUtils from '../../Utils/randomUtils';
import config from '../../Configs/GlobalConfig';
import LoadingModal from '../LoadingModal';


@inject('store')
@observer
export default class MediaList extends React.Component {
  constructor() {
    super();
    this.state = {
      refreshing: false,
      currentlyLoadingText: '',
    }
  }

  async componentDidMount() {
    console.warn(this.props.store.mediaList);
    await this.refreshFiles();
  }

  showAlertNoFiles = () => {
    Alert.alert(
      '',
      'No files found',
      [
        {text: 'OK', onPress: () => {}, style: 'cancel'}
      ],
      { cancelable: false }
    )
  };


  fileAlreadyExists = file => {
    let exists = false;

    mobx.toJS(this.props.store.mediaList).forEach(existingMedia => {
      if (path.basename(existingMedia.path, '.unzipped') === file) {
        exists = true;
      }
    });

    return exists;
  };


  getLocalFiles = async () => {
    return new Promise(async (resolve, reject) => {
      try {
        const files = await fs.readdir(config.directories.EXT_MEDIALIST_DIR);
        files.forEach(file => {
          if (path.extname(file) === '.unzipped') {
            if (!this.fileAlreadyExists(path.basename(file, '.unzipped'))) {
              this.setState({ currentlyLoadingText: `Loading ${path.basename(file, '.unzipped')} from storage`});
              this.props.store.addMedia({
                path: config.directories.EXT_MEDIALIST_DIR + '/' + file
              })
            }
          }
        });
        resolve();
      } catch (err) {
        console.warn(err);
        reject(err);
      }
    });
  };


  getRemoteFiles = async () => {
    return new Promise(async (resolve, reject) => {
      try {
        const res = await FtpService.listFiles(this.props.store.user.phone_number);
        let files = randomUtils.parseDirectoryListing(res.data);

        // Do not process files we already have
        files = files.filter(file => {
          if (mobx.toJS(this.props.store.mediaList)) {
            return !this.fileAlreadyExists(file);
          }
        });

        for (let file in files) {
          this.setState({ currentlyLoadingText: `Downloading ${path.basename(files[file], 'unzipped')} from server`});
          await FtpService.downloadFile(this.props.store.user.phone_number, files[file]);
        }
        resolve();
      } catch (err) {
        this.showAlertNoFiles();
        reject(err);
      }
    });
  };

  refreshFiles = async () => {
    if (this.state.refreshing) {
      return;
    }

    this.setState({ refreshing: true });
    try {
      await this.getLocalFiles();
    } catch (err) {
      console.warn(err);
    }
    try {
      await this.getRemoteFiles();
    } catch (err) {
      console.warn(err);
    }
    this.setState({ refreshing: false, currentlyLoadingText: '' });
  };

  deleteItem = (item) => {
    this.props.store.removeMedia(item);
    fs.unlink(item.path);
  };

  onSelectMedia = (item) => {
    this.props.store.setCurrentMedia(item);
    Actions.push('mediaPresenter');
  };

  renderMediaItem = (item) => {
    let previewPath = 'file://' + item.path + '/preview.jpeg';
    return (
      <Swipeable rightButtons={[this.renderDeleteItem(item)]}>
        <TouchableHighlight underlayColor={'orange'} onPress={() => { this.onSelectMedia(item) }} style={styles.buttonBackground}>
          <View style={styles.row}>
              <Image source={{uri: previewPath}} style={styles.previewThumbnail}/>
              <Text style={styles.titleText}>{path.basename(item.path).replace('.unzipped', '')}</Text>
          </View>
        </TouchableHighlight>
      </Swipeable>
    );
  };

  renderDeleteItem = (item) => {
    return (
      <TouchableHighlight underlayColor={'orange'} onPress={() => {this.deleteItem(item)}} style={styles.buttonBackground}>
        <Image source={require('../../../assets/images/delete.png')} style={styles.deleteIcon}/>
      </TouchableHighlight>
    );
  };

  render() {
    let mediaList = [];
    try {
      mediaList = mobx.toJS(this.props.store.mediaList);
    } catch (err) {
      console.warn(err);
    }
    return (
      <ImageBackground source={config.backgroundImage}
                       style={styles.background}>
        <View style={styles.container}>
          <Text style={[styles.grey, styles.centerText, styles.smallPadding]}>Pull to refresh</Text>
          <FlatList
            data={ mediaList }
            keyExtractor={ item => item.index.toString() }
            renderItem={ ({item}) => this.renderMediaItem(item) }
            backgroundColor={'transparent'}
            refreshControl={
              <RefreshControl
                refreshing={this.state.refreshing}
                onRefresh={() => { this.refreshFiles() }}
                title="Checking for new files..."
                tintColor="orange"
                titleColor="#fff"
              />
            }
          />
        </View>
        <LoadingModal loading={this.state.refreshing} text={this.state.currentlyLoadingText} />
      </ImageBackground>
    );
  }
}

0 ответов

Другие вопросы по тегам