如何制作一个 React Native 组件数组?

How to make an array of React Native components?

我正在尝试在我的观点 (docs) 中使用 react-native-table-component,但我 运行 遇到了问题,因为我希望我的专栏包含图像组件。我遵循了使用按钮的文档中的示例,并且有这样的内容:

    console.log("following pic arr: " + this.state.followingPics);
    var following_pics;
    if(this.state.followingPics.length === 0) {
        following_pics = [];
    }
    else {
        //this.state.followingPics is an array of picture urls
        JSON.parse(this.state.followingPics).forEach((pic, i) => {
            following_pics.push(makeImage(pic));
        })
    }

    var tableArr = [following_pics, following];

    return (
        <View style={shared.basicView}>
            <TextInput
                autoCorrect={false}
                style={{height: 40}}
                placeholder="Follow a user..."
                onSubmitEditing={(input) => this.addFollower(input.nativeEvent.text)}
            />
            <Table style={styles.table}
                   borderStyle={{borderWidth: 0.5, borderColor: '#c8e1ff'}}>
                <Row data={tableHead}
                     style={styles.head} textStyle={styles.text}
                     flexArr={[1]}
                />
                <Cols data={tableArr}
                      textStyle={styles.text}
                      heightArr={[50, 50, 50, 50, 50, 50, 50, 50]}
                      flexArr={[1, 2, 1, 2]}
                />
            </Table>
        </View>
    );

但我一直收到错误提示 undefined is not an object (evaluating following_pics.push)。有什么方法可以将这些图片添加为指定的数据数组吗?

您在 else 块中所做的是您尝试将 push 元素添加到未定义的变量中:

console.log("following pic arr: " + this.state.followingPics);
var following_pics;  // this will be undefined in else block
if(this.state.followingPics.length === 0) {
    following_pics = [];
}
else {
    //this.state.followingPics is an array of picture urls
    JSON.parse(this.state.followingPics).forEach((pic, i) => {
        following_pics.push(makeImage(pic));
    })
}

我不明白你为什么需要这个 if 块,为什么不只是:

console.log("following pic arr: " + this.state.followingPics);
var following_pics = [];
//this.state.followingPics is an array of picture urls
JSON.parse(this.state.followingPics).forEach((pic, i) => {
   following_pics.push(makeImage(pic));
})