在React native中动态导入JSON文件



我想根据特定条件动态导入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((函数中放入什么。

您可以使用require。

创建的博览会小吃:

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

最新更新