LOCAL JSON与外部文件

时间:2018-06-06 14:23:58

标签: react-native

我在这里发现了一篇帖子,其中建议如何使用本地json文件来处理本地的数据。它建议我使用var custom data = {filename} ..但是我似乎无法让它个人工作......我想知道是否有人可以帮助我。这是代码

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
}]
}

我不确定这是我的平面列表的问题,还是我错误地提取数据..

1 个答案:

答案 0 :(得分:0)

您必须导出数据:

data.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)
  }
}