2017-08-05 98 views
0

我想從我的本地文件系統使用 react-native-fs讀取文本文件。然而,它一直告訴我該文件不存在(它確實,我仔細檢查了它,並試圖將其複製到運行窗口中)。閱讀本地文件反應原生

'use strict'; 

import React, { Component } from 'react'; 
//import FileSystem from 'react-native-filesystem'; 

import RNFS from 'react-native-fs'; 

import { 
    AppRegistry, 
    StyleSheet, 
    Text, 
    View, 
    NetInfo 
} from 'react-native'; 


export default class FactsApiFetcher extends Component 
{ 
    constructor(props) 
    {  
    super(props); 
    this.state = 
    { 
     fact: 'Loading...' 
    } 
    } 

    componentWillMount() 
    { 
    this._getRandomFact(); 
    } 

    _getRandomFact() 
    { 
    const fileContents = RNFS.read("D:\\AllRand\\facts-api-handler\\test.txt") //FileSystem.readFile("D:\\AllRand\\allfacts\\test.txt");  

    this.setState({ 
     fact: fileContents 
    }) 
    } 

    render() 
    {  
    return <Text> { this.state.fact } </Text>; 
    } 
} 


AppRegistry.registerComponent('FactsApiFetcher',() => FactsApiFetcher); 
+0

您是否設置了配置? https://github.com/itinance/react-native-fs#usage-android,那裏也有一個例子用法。 –

+1

從文檔https://github.com/itinance/react-native-fs#readfilepath-string-length--0-position--0-encodingoroptions-any-promisestring你需要返回承諾,當使用方法'讀( )' –

回答

3

您應該將文件捆綁到應用程序中或手動將它們放入模擬器或設備中。當你運行應用程序時,它可能只探索它自己的文件系統,並且它不能檢測你的Windows FS。使用這個常量https://github.com/itinance/react-native-fs#constants來訪問文件。