如何将 new array() 与 .map 一起使用



我想像这样使用 .map。我像新数组(4(一样定义数组,但我不给出任何项目。所以当我这样使用时:

      imgUrls.map((url, index) => {
..
});

*这不会运行 4 次。 为什么?我有默认的img,所以如果imgUrls的第一个项目是空的,那么使用默认图像。如果秒为空,则使用默认图像...它应该是这样的,但我无法解决*

我尝试的代码如下

 constructor(props) {
        super(props);
        this.state = {
          imgUrls: new Array(4),  
          defaultImage: require('../Images/addcircle.png'),   
        };
      }
renderContent = () => {
        const { imgUrls } = this.state;
            return imgUrls.map((url, index) => {
                try {
                    return (
                        <View key={index} >
                          <TouchableOpacity onPress={() => this.removeImg(index)}>
                            <View style={{ height: '100%', justifyContent: 'center', alignItems: 'center', aspectRatio: 1 }}>                  
                                            <Image
                                            source={{ uri: url } || this.state.defaultImage}
                                            style={{ height: '90%', width: '90%' }}
                                            /> 
                            </View>
                          </TouchableOpacity>
                        </View>
                        );
                } catch (error) {
                    console.log('error:', error);
                }
            }); 
      };

 render() {
        console.log('in bar');             
        return (
            <View style={styles.container}>
             {this.renderContent()} 
            </View>
)
}

这个创建一个空的arry,你可以映射到:)

const arr = Array.apply(null, Array(5));
arr.map(() => {}) // <- this one will work

这个创建了一个您无法映射的空 arry

const arr = new Array(5);
arr.map(() => {}) // <- this one will not work

最新更新