首页 > 解决方案 > 在 React 中以 Modal 形式显示相同的数据

问题描述

嗨,我正在开发一个在线商店反应项目,我的职责是为产品添加折扣。

为此,我开发了一个包含产品详细信息的组件,包括添加折扣按钮。一旦我们单击按钮,它就会将我们带到一个模态表单,我们可以在其中为产品添加折扣。就是这么简单。

这是我的组件代码。

    import React, { Component } from 'react';
    import {Link} from 'react-router-dom';
    import { getCategories, getProducts } from "../core/apiCore";
    import EditProduct from './EditProduct';


    const Product = props =>{

        return(
        <tr>
            <td>{props.product.category.name}</td>
            <td>{props.product.name}</td>
            <td>{props.product.quantity}</td>
            <td>Rs.{props.product.price}</td>
            <td>%</td>
            <td>

                <button type="button" className="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
                    Add Discount
                </button>
                <EditProduct Currentproduct={props.product.name}/>
            </td>
        </tr>
        );

    }

    export default class AddDiscount extends Component{

        constructor(props){
            super(props)

            this.state={
                products:[]
            }
        }

        componentDidMount(){
            getProducts()
                .then(resultProducts=>{
                    this.setState({
                        products:resultProducts
                    })
                    console.log(resultProducts)
                });

        }

        productList=()=>{
            return this.state.products.map(Currentproduct=>{
                return <Product product={Currentproduct} key={Currentproduct._id}/>
            })
        }

        render(){
            return(
                <div>
                    <h3>Product Details</h3>
                    <table className="table">
                        <thead className="thead-light">
                            <tr>
                                <th>Product Category</th>
                                <th>Product Name</th>
                                <th>Quantity</th>
                                <th>Price</th>
                                <th>Discount</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            {this.productList()}
                        </tbody>
                    </table>
                </div>
            )


   }
}

在上面的代码中,我在同一个文件中使用了功能组件和类组件,我所做的是创建了一个表,其中包含来自数据库的产品详细信息,并且每个产品都使用产品组件进行迭代和显示。

产品组件显示表格所需的详细信息,我还添加了一个添加折扣按钮,该按钮显示一个带有产品详细信息的模式表单和一个输入折扣的字段。这个模态表单是在 EditProduct 组件内部开发的。

我刚刚将产品名称作为道具发送到 EditProduct 组件,以便我可以测试当我们单击“添加折扣”按钮时模型表单中是否显示了不同的数据。

我的问题是,当我单击按钮添加新折扣模式表单时,只显示表中第一项的数据?为什么会这样,我该如何改变它?

请为此提供解决方案。提前致谢。

标签: javascriptreactjs

解决方案


推荐阅读