如何比较两个数组的值,如果两者都相等则返回diff。按钮

问题描述 投票:0回答:1

我正在渲染一个Flatlist,我希望根据按钮的ID是否在我的购物车中显示一个按钮。我怎么能这样做....

这是我的按钮代码:

addBtn = (id) => {

        try{
            let productAdded = this.state.addedToCart;
            return productAdded.map((pid) => {
                if (pid == id) {
                    // console.log(pid);
                    // console.log("-----------");
                    console.log(id + " is added into cart");
                    return(
                        <Button
                            key={id}
                            style={{ 
                                backgroundColor: '#fff',
                                borderWidth: 2,
                                borderColor: '#2e6153',
                                borderStyle: 'solid',
                            }}
                        >
                            <Text style={{color: '#2e6153',}}>Added</Text>
                        </Button>
                    );
                } else {
                    console.log("not added to cart");
                    return(
                        <Button
                            key={id}
                            onPress={() => {
                                this.saveCart(id);
                            }} 
                            style={{ 
                                backgroundColor: '#2e6153',
                                borderWidth: 2,
                                borderColor: '#2e6153',
                                borderStyle: 'solid',
                                width: 80,
                                alignItems: 'center',
                                justifyContent: 'center',
                            }}
                        >
                            <Text>Add</Text>
                        </Button>
                    );
                }
            });
        }catch(errors){
            console.log(errors);
        }

    }

其中“addBtn =(id)”的id来自FlatList的renderItem。

和this.state.addedToCart是我的购物车中的项目数组。目前我在购物车中添加了两个商品,所以this.state.addedToCart = [“1015”,“1016”]

和输出是:Here is the image of my output

我想只渲染一次,但按钮的渲染次数与我的购物车尺寸相同。

javascript reactjs react-native react-native-android react-native-ios
1个回答
0
投票

我猜有一个问题:

return productAdded.map((pid) => {

只需将其删除并将if语句更改为:

if (productAdded.includes(id)) {

所以它只会返回一个按钮

© www.soinside.com 2019 - 2024. All rights reserved.