如果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数组用于ScrollView中的列表.txt文件

render() {
    return(
        ....
        <ScrollView>
            {
                items.map((items) => this.renderItem(items))
            }
        </ScrollView>
        ....
    );
}

最佳答案

尝试:

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);
        }

    }
    console.warn(items); // empty
})
.catch((err) => {
    console.log(err.message, err.code);
});


}


您的诺言运行异步=> console.warn在诺言解决之前被调用(.then(...))

07-24 16:20