简体   繁体   中英

Import JSON file dynamically in React-native

I want to import JSON files dynamically based on certain condition. My Code is

import TXT1 from "../Assets/TTCS1.json";
import TXT2 from "../Assets/TTCS2.json";

export class Timetable extends Component {
  state = {class: 1}; 
  render() {
    return this.state.class === 1 ? (
        <View style={styles.container}>
          <Text>{TXT1.S5}</Text>
        </View>
    ) : (
      <View style={styles.container}>
        <Text>{TXT2.S5}</Text>
      </View>
    );
  }
}

These JSON files are large and a particular user will mostly use only any one of the JSON file hence importing all is waste of resources. I found an answer here How can I conditionally import an ES6 module? the answer works fine with JS files, but with JSON files I am confused what is to be put in.then() function.

you can use require.

Created expo snack:

https://snack.expo.io/BJRqgSnqr

import React, { Component } from 'react';
import { Text, View, StyleSheet, ScrollView } from 'react-native';
import * as Constants from 'expo-constants';

var TXT1='',TXT2='';

export default class App extends Component {

  state={TXT1:'',TXT2:''}

  componentDidMount=()=>
  {

     TXT1  = require('./assets/TXT1.json');
     this.setState({TXT1});
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>{JSON.stringify(this.state.TXT1)}</Text>
        <Text>{JSON.stringify(TXT2)}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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