阅读本地文件反应原生
问题描述:
我想从我的本地文件系统使用 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);
答
您应该将文件捆绑到应用程序中或手动将它们放入模拟器或设备中。当你运行应用程序时,它可能只探索它自己的文件系统,并且它不能检测你的Windows FS。使用这个常量https://github.com/itinance/react-native-fs#constants来访问文件。
您是否设置了配置? https://github.com/itinance/react-native-fs#usage-android,那里也有一个例子用法。 –
从文档https://github.com/itinance/react-native-fs#readfilepath-string-length--0-position--0-encodingoroptions-any-promisestring你需要返回承诺,当使用方法'读( )' –