本地 JSON 与外部文件



我在这里找到了一篇文章,建议如何在 react native 中使用本地 json 文件作为数据。它建议我使用 var 自定义数据 = {文件名}。但是我似乎无法亲自让它工作...我想知道是否有人可以帮助我。这是代码

const customData = require('../dr.json')
export default class DailyReportListScreen extends React.Component {

static navigationOptions = ({navigation}) => {
const params = navigation.state.params || {}
console.log(params)
return {
headerTitle: 'Daily Reports',
headerRight: (
<Button title="Log out" onPress={() => 
navigation.navigate('AddDailyReportForm')} color="#a41034" />
),
}   
}
state = {
data = [customData]
};
constructor(props){
super(props);
this.state ={ isLoading: true}
data: [customData]
}
componentWillMount() {
this.setState({data: this.customData});
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
keyExtractor={(x, i) => i}
renderItem={({ data }) =>
<Text>
{data.data.name}
</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 15,
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
}
});

以下是 json 数据:

{
"recordcount": 25015,
"data": [{
"name": "joe"
"number": 12
},
{
"name": bill
"number": 5
}]
}

我不确定这是否是我的平面列表的问题,或者我是否错误地提取了数据。

您必须导出数据:

数据.js:

export const DATA = {
'recordcount': 25015,
'data': [
{
'name': 'joe',
'number': 12,
},
{
'name': 'bill',
'number': 5,
}
]
}

并像这样正确导入它:

import { DATA } from '../path/to/local/file/data.js'
export default class DailyReportListScreen extends React.Component {
componentDidMount() {
console.log(DATA)
}
}

最新更新