如何在.map中使用new array()?

时间:2019-04-04 11:14:03

标签: react-native

我想这样使用.map。我定义了像new array(4)这样的数组,但我没有给出任何内容。所以当我这样使用时:

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

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

我尝试的代码如下

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

1 个答案:

答案 0 :(得分:1)

这会创建一个空的棚屋,您可以在上面绘制:)

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

这会创建一个空的杂物,您无法映射

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