如何在react中不同页面中存在的不同组件之间移动道具(道具钻取)数据

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

我正在尝试将

newItems, setNewItems
[newItems, setNewItems] = useState([]);
值移动为正在构建的应用程序上另一个网页中使用的组件的道具,想法是这样的,而在新页面中,我想循环
 的值newItems
数组并返回项目列表的 JSX 显示。我目前没有使用数据库。我想知道我是否以错误的方式这样做,是否可以做到。谢谢。我得到的错误是地图无法读取
newItems
的内容。并且
newItems
的内容在控制台中显示为空,错误指向
MoneyInOutDetails
组件

//MoneyIn Component

const MoneyIn = ({newItems, setNewItems}) => {

 let handleSaveMonyIn = (event) => {
        event.preventDefault(); 
        //setBalanceDue(balanceSet);
        if (totalAmountIn === 0 || itemDescription === "") {
            setSeverity("error")
            //setError(true);
            setMessage("Enter Amount and Item Description");
            setOpen(true)
        } else if (totalSellingPrice > totalAmountIn) {
            console.log(totalSellingPrice);
           // setError(true);
            setSeverity("error")
            setMessage("Total Selling Prices cannot be bigger than Total amount");
            setOpen(true)
        }

        else {
            const newMoneyInData = { totalAmountIn, amountRecieved, balanceDue, newItems, itemDescription };
            setMoneyInData([...moneyInData, newMoneyInData]);

            localStorage.setItem("moneyIn", JSON.stringify(moneyInData));
            document.getElementById("totalAndRecievedAmt").reset();
            document.getElementById("itemDescriptionFrm").reset();
            //setSuccess(true);
            setSeverity("success");
            setMessage("Saved Successfully !!!");
            setOpen(true);
            // setTotalAmountIn(0);
            // setAmountRecieved(0);
            // setBalanceDue(0);
            // setItemDescription('');
             // setNewItems([]);

            
            console.log(newMoneyInData);
        }
      
    }

let handleSaveItem = () => {
        const newItemData = { productName, sellingPriceOfTotal, quantityCount, sellingPrice };
        setNewItems([...newItems, newItemData]);
        console.log(newItemData);
    }
 let handleSaveItemOnclick = () => {
        if (sellingPriceOfTotal > totalAmountIn) {
            console.log(totalAmountIn);
            console.log(sellingPrice);
            console.log("Alert is working");
           // setError(true);
            setSeverity("error")
            setMessage("Selling Price cannot be bigger than Total");
            setOpen(true)

            // setOpen(false)

        } else if (sellingPrice === 0 || productName === "") {
            console.log(sellingPrice);
            console.log(productName);
            setSeverity("error")
            //setError(true);
            setMessage("Product name and Selling price cannot be empty");
            setOpen(true)
        } else {
            handleSaveItem()
            setVisible(!visible)
            setProductName("");
            setSellingPrice(0);
            setQuantityCount(1);
        }
    }

return (
                <div>
                    <div>Items</div>
                    <ItemLists newItems={newItems} handleDelete={handleDelete}/>
                    <div className='totalItemsAdded'>
                        <p>Total</p>
                        <p>${totalSellingPrice}</p>
                    </div>
                </div>
            );
     
}

//ItemList Component

const ItemLists = (props) => {
  
    const newItems = props.newItems;
    const handleDelete =  props.handleDelete;
   
  console.log(newItems);
   
  return (
 

    <div>
        
         {newItems.map((items) => {
                        const { productName, sellingPriceOfTotal, quantityCount, sellingPrice } = items;
                        return (
                            <>
                                <div className='itemsAdded'>
                                    <div className='eachItemAdded'><div>{productName}</div>
                                        <div>{sellingPriceOfTotal} = {sellingPrice} x {quantityCount}</div>
                                    </div>
                                    <div className='deleteEditFont'><FontAwesomeIcon icon={faTrashCan} onClick={() => handleDelete(items)} /></div>

                                </div>

                            </>
                        );
                    })}

    </div>
     

  )
}

export default ItemLists

//App.js Component

const App = () => {
  const [newItems, setNewItems] = useState([]);
 // localStorage.setItem("newIt", JSON.stringify(newItems));

    console.log(newItems);
  return (
    <>
     <Router>
      <Routes>
        <Route path='/' exact element={<Home newItems = {newItems} setNewItems={setNewItems}/>} />
        <Route path='/moneyIn' element={<MoneyIn newItems = {newItems} setNewItems={setNewItems}/>} />
      </Routes>
     </Router>
    </>
  )
}

export default App

//Home Component

const Home = ({newItems, setNewItems}) => {
  return (
    <>
    <div className='allBodyCards'>
   <Balances/>
   <div className='transactions'>
   <DailyTransactions />
   <MoneyInOutDetails newItems={newItems} setNewItems={setNewItems}/>
   </div>
   </div>
   
   </>
  )
}

export default Home

//MoneyInOutDetails Component Where am running the map to list items in JSX

const MoneyInOutDetails = ({newItems, setNewItems}) => {
     console.log(newItems);
    newItems.map((items) => {
        const { productName, sellingPriceOfTotal} = items;
        return (
       <div className='moneyInOutWrapper'>
            <div>{productName}</div>
            <div className='amountAndIcons'>
                <div className='amountInOut'>${sellingPriceOfTotal}</div>
                <div className='deleteEditIcons'>
                    <FontAwesomeIcon icon={faPenToSquare} />
                    <FontAwesomeIcon icon={faTrashCan} />
                </div>
            </div>

        </div>
    ) })
}

export default MoneyInOutDetails

javascript reactjs jsx react-props prop
1个回答
0
投票

这不是一个答案,更像是一条评论
我没有足够的声誉来发表评论
从您提供的代码来看,

newItems
最初被初始化为空数组。您为其设置值的唯一位置是在
handleSaveItem()
组件
 下的 
MoneyIn
函数中 如果您在
newItems
中给它赋值之前尝试访问
handleSaveItem
,那么它仍然是空的

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.