如果componentWillMount()
函数第一次运行,items
则数组为空。为什么?
componentWillMount() {
items.splice(0, items.length);
RNFS.readDir(RNFS.DocumentDirectoryPath)
.then((result) => {
console.warn('result: ', result); // debug
for(var i = 0; i < result.length; i++) {
if(result[i].name.endsWith('.txt')) {
var tmp = result[i].name;
console.warn(tmp); // debug
items.push(tmp);
}
}
})
.catch((err) => {
console.log(err.message, err.code);
});
console.warn(items); // empty
}
并且readFile()
用于获取 .txt 的内容,con
是空的
renderItem(item) {
return (
<View style = {styles.renderItemContainer}
key={items.indexOf(item)} >
<TouchableOpacity style={styles.renderItemTouchableOpacity}
onPress = {() => {
fileName = item;
var path = RNFS.DocumentDirectoryPath + '/' + fileName;
RNFS.readFile(path, 'utf8')
.then((contents) => {
console.warn(contents);
con = contents; // not working
})
.catch((err) => {
console.log(err.message, err.code);
});
console.warn(con); // empty
this.props.navigation.navigate('editorScreen');
}}>
<Text style = {styles.renderItemText}>
{item}
</Text>
</TouchableOpacity>
</View>
);
}
在render()
函数中,使用items
数组列出 .txt 文件ScrollView
render() {
return(
....
<ScrollView>
{
items.map((items) => this.renderItem(items))
}
</ScrollView>
....
);
}