繁体   English   中英

React-native中动态导入JSON文件

[英]Import JSON file dynamically in React-native

我想根据特定条件动态导入 JSON 文件。 我的代码是

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>
    );
  }
}

这些 JSON 文件很大,特定用户大多只会使用 JSON 文件中的任何一个,因此导入所有文件都是浪费资源。 我在这里找到了答案如何有条件地导入 ES6 模块? 答案适用于 JS 文件,但对于 JSON 文件,我很困惑要放入什么。then() function。

你可以使用要求。

创建 expo 零食:

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',
  },

});

暂无
暂无

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

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