React Native Redux 购物车应用问题

如何解决React Native Redux 购物车应用问题

我正在尝试制作一个应用程序,允许用户在我的 DetailsComponent.js 页面中选择“添加到购物车”。我目前正在更新我的商店中名为“cart”的数组,其 ID 对应于商店内产品数组中的产品。我已经检查了调试器,并且产品 ID 已正确添加到购物车数组中。 我正在使用以下代码在我的购物车页面上显示与我的购物车中的产品 ID 匹配的产品,但我的购物车目前没有显示任何内容。

CartComponent.js

import React,{ Component } from 'react';
import { FlatList,View,Text,Alert } from 'react-native';
import { ListItem } from 'react-native-elements';
import { connect } from 'react-redux';
import { baseUrl } from '../shared/baseUrl';
import { Loading } from './LoadingComponent';
import { removeCart } from '../redux/ActionCreators';


const mapStateToProps = state => {
    return {
        products: state.products,cart: state.cart
    }
}

const mapDispatchToProps =  dispatch => ({
    removeCart: (id) => dispatch(removeCart(id))
});

class CartScreen extends Component {
    
    render() {

        const renderMenuItem = ({item,index}) => {
            return(
               <ListItem 
                    key={index}    
                    bottomDivider
                >
                   <ListItem.Content>
                        <ListItem.Title>
                            {item.name}
                        </ListItem.Title>
                        <ListItem.Subtitle>
                            {item.quantity} chargers: ${item.price}
                        </ListItem.Subtitle>
                   </ListItem.Content>
                   
               </ListItem>
            );
        }
        if (this.props.cart.isLoading) {
            return(
                <Loading />
            )
        }
        else if (this.props.cart.errMess) {
            return(
                <Text>{this.props.cart.errMess}</Text>
            )
        }
        else {
            return(
            <View>
                <Text>
                    Cart
                </Text>
                <FlatList
                    data={this.props.products.products.filter(product => this.props.cart.cart.some(el => el === product.id))}
                    renderItem={renderMenuItem}
                    keyExtractor={item => item.id.toString()}
                />
            </View>
            );
        }
    }
}
export default connect(mapStateToProps,mapDispatchToProps)(CartScreen);

我已经包含了我的其他文件以获取更多信息。

我有不同的 DropDownPicker 值对应于我的 redux 商店中的产品 ID。商店中的这些商品具有要在 CartComponent.js 中使用的数量和价格值。

DetailsComponent.js

import React,{ Component } from 'react';
import { Text,Image,Button,FlatList,StyleSheet,ScrollView} from 'react-native';
import DropDownPicker from 'react-native-dropdown-picker';
import { baseUrl } from '../shared/baseUrl';
import { connect } from 'react-redux';
import { Loading } from './LoadingComponent';
import { postCart } from '../redux/ActionCreators';


const mapStateToProps = state => {
    return{
        chargers: state.chargers,utensils: state.utensils,orders: state.orders,products: state.products
    }
}

const mapDispatchToProps = dispatch => ({
    postCart: (id) => dispatch(postCart(id))
})

class DetailsScreen extends Component {
    constructor(props) {
        super();
        this.state = {
            itemId: '',orderAmount: '',orderPrice: ''
        }
    }

    addToCart(id) {
        this.props.postCart(id);
    }

    render() {
        const categoryName = this.props.route.params.categoryName;
        const productId = this.props.route.params.menuId;                  
        const item = this.props[categoryName][categoryName][productId];
        if (categoryName === "chargers") {
            if (productId === 0) {
                var amounts = [
                    {label: '50',value: '1'},{label: '100',value: '2'},{label: '150',value: '3'},{label: '200',value: '4'},{label: '250',value: '5'},{label: '300',value: '6'},{label: '350',value: '7'},{label: '400',value: '8'},{label: '450',value: '9'},{label: '500',value: '10'},{label: '550',value: '11'},{label: '600',value: '12'},];
            }
            else if (productId === 1) {
                var amounts = [
                    {label: '50',value: '14'},value: '15'},value: '16'},value: '17'},value: '18'},value: '19'},value: '20'},value: '21'},value: '22'},value: '23'},value: '24'},value: '25'},];
            }
            else if (productId === 2) {
                var amounts = [
                    {label: '50',value: '27'},value: '28'},value: '29'},value: '30'},value: '31'},value: '32'},value: '33'},value: '34'},value: '35'},value: '36'},value: '37'},value: '38'},];
            }
        }
        else if (categoryName === "utensils") {
            if (productId === 0) {
                var amounts = [
                    {label: '1',value: '40'},{label: '2',value: '41'},{label: '3',value: '42'},{label: '4',value: '43'},{label: '5',value: '44'},];
            }
            else if (productId === 1) {
                var amounts = [
                    {label: '1',value: '46'},value: '47'},value: '48'},value: '49'},value: '50'},];
            }
                
        }
        
        
        if (this.props[categoryName].isLoading) {
            return(
                <Loading />
            )
        }
        else if (this.props[categoryName].errMess) {
            return(
                <Text>
                    {this.props[categoryName][categoryName].errMess}
                </Text>
            )
        }
        else {
            return(
                <ScrollView>
                    <Text style={styles.title}>
                        {item.name}
                    </Text>
                    <Text>
                        {item.category}
                    </Text>
                    <View style={{flex: 1,flexDirection: 'row'}}>
                        <Image
                            style={styles.image}
                            source={{uri: baseUrl + item.image}}
                        />
                        <DropDownPicker
                            items={amounts}
                            defaultNull
                            placeholder="Select amount"
                            containerStyle={{height: 40,width: 100}}
                            itemStyle={{
                                justifyContent: 'flex-start'
                            }}
                            onChangeItem={item => this.setState({
                                itemId: this.props.products.products[item.value].id,orderAmount: this.props.products.products[item.value].quantity,orderPrice: this.props.products.products[item.value].price
                            })}
                        />
                    </View>
                    
                    <Text>
                        {item.description}
                    </Text>
                    
                    <Text>
                        Your order is {this.state.orderAmount} {this.props[categoryName][categoryName][productId].name} chargers for ${this.state.orderPrice}
                    </Text>
                    <Button
                        title='Add to Cart'
                        color="#f194ff"
                        onPress={() => this.addToCart(this.state.itemId)}
                    />
    
                </ScrollView>
            )
        }
        
    }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,},image: {
        resizeMode: "contain",height: 200,width: 200
    },title: {
      fontSize: 32,});

export default connect(mapStateToProps,mapDispatchToProps)(DetailsScreen);

以下代码示例是我的 redux 文件。为了便于阅读,我仅使用购物车信息对其进行了简化。

ActionCreators.js

export const fetchCart = () => (dispatch) => {
    
    dispatch(cartLoading());

    return fetch(baseUrl + 'cart')
    .then(response => {
        if (response.ok) {
            return response;
        } else {
            var error = new Error('Error ' + response.status + ': ' + response.statusText);
            error.response = response;
            throw error;
        }
        },error => {
            var errmess = new Error(error.message);
            throw errmess;
        })
    .then(response => response.json())
    .then(cart => dispatch(addCart(cart)))
    .catch(error => dispatch(cartFailed(error.message)));
};

export const cartLoading = () => ({
    type: ActionTypes.CART_LOADING
});

export const cartFailed = (errmess) => ({
    type: ActionTypes.CART_FAILED,payload: errmess
});

export const postCart = (id) => (dispatch) => {
    const newCart = {
        id: id
    };
    setTimeout(() => {
        dispatch(addToCart(newCart));
    },2000);
};

export const addToCart = (cart) => ({
    type: ActionTypes.ADD_TO_CART,payload: cart
});

export const addCart = (id) => ({
    type: ActionTypes.ADD_CART,payload: id
});

export const removeCart = (id) => ({
    type: ActionTypes.REMOVE_CART,payload: id
});

ActionTypes.js

export const POST_CART = 'POST_CART';
export const ADD_TO_CART = 'ADD_TO_CART';
export const ADD_CART = 'ADD_CART';
export const REMOVE_CART = 'REMOVE_CART';
export const CART_LOADING = 'CART_LOADING';
export const CART_FAILED = 'CART_FAILED';

cart.js

import * as ActionTypes from './ActionTypes';

export const cart = (
    state = { 
        isLoading: true,errMess: null,cart:[]
    },action) => {
        switch (action.type) {
            case ActionTypes.ADD_CART:
                return {...state,isLoading: false,cart: action.payload};
    
            case ActionTypes.CART_LOADING:
                return {...state,isLoading: true,cart: []};
    
            case ActionTypes.CART_FAILED:
                return {...state,errMess: action.payload};

            case ActionTypes.ADD_TO_CART:
                var newCart = action.payload;
                return {...state,cart: state.cart.concat(newCart) };
    
            default:
                return state;
        }
    };

以下是我的 db.json 文件。我已将一项项目输入到购物车数组中进行测试,但它也没有显示在购物车中。还简化了此文件以仅显示少数产品以提高可读性。

"products": [
        {
            "id": 0,"name": "Ezywhip Pro","category": "chargers","label": "","featured": false,"description": "Ezywhip Pro Cream Chargers,Made by MOSA","image": "images/ezywhip.png","quantity": 0,"price": 0
        },{
            "id": 1,"category": "ezy","quantity": 50,"price": 40
        },{
            "id": 2,"quantity": 100,"price": 70
        },{
            "id": 3,"quantity": 150,"price": 110
        }
    ],"cart": [
        {
            "id": 1
        }
    ]
}

如果有人能解释我做错了什么,将不胜感激。

解决方法

我通过更改以下内容使其工作:

export const addToCart = (id) => ({
    type: ActionTypes.ADD_TO_CART,payload: id
});

不确定这是否会导致任何问题,但为了安全起见,我将其更改为 id。

这就是导致主要问题的原因,我需要使用 el.id 来指定我在数据中与之比较的内容。

<FlatList
  data={this.props.products.products.filter(product => this.props.carts.carts.some(el => el.id === product.id))}
  renderItem={renderMenuItem}
  keyExtractor={item => item.id.toString()}
/>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-