[英]How to pass useState Value from One Component to another one in React.js
[英]how to pass useState variable value to array of object field for INSERT data react.js and mysql?
**我有一個帳單表格,在此我有一些產品詳細信息,管理員可以填寫這些詳細信息,但是有一個名為“BillID”的字段我想直接將一個包含“Bill ID + 1”值作為默認值的變量傳遞給它.
**這是我的代碼:-
const [BillIdFetch, setBillIdFetch] = useState();
useEffect(() => {
axios.get("http://localhost:5000/getLastBill_Id").then(( res ) => {
setBillIdFetch(res.data[0].Bill_Id + 1);
});
}, []);
console.log("===>>>> Testing BillIdFetch ",BillIdFetch) //**I check in this variable value stored perfectly.
const [Product_Details, setProduct_Details] = useState([
{
index: Math.random(),
billId : BillIdFetch, //**I want 'BllIdFetch' value pass to this state variable.
prodId: "",
qty: "",
price: "",
prod_SrNo: "",
discount_price: "",
proData_warranty: "",
},
]);
在“BillIdFetch”中,我得到了正確的 id + 1 值,我也使用這個值來顯示賬單號。 在表單列中。 但是當我將此值設置為“billId”時,它顯示如下:- {billId: undefined}
這是對服務器的發布請求。
在此將對象的“Produt_Details”數組傳遞給它。
const config = {
header: {
"Content type": "appication/json",
},
};
const { data } = await axios.post(
"http://localhost:5000/billing_data",
{ p_value: Product_Details },
config
);
您需要做的是檢查BillIdFetch
更改,然后為Product_Details
設置正確的狀態值。 在您當前的代碼中,設置Product_Details?
將在獲取之前運行。
為了解決這個問題,使用帶有BillIdFetch
的useEffect
掛鈎作為依賴項,因此,當BillIdFetch
更改時,此代碼將運行。
它可能看起來像這樣:
const [Product_Details, setProduct_Details] = useState([]);
const [BillIdFetch, setBillIdFetch] = useState();
useEffect(() => {
axios.get("http://localhost:5000/getLastBill_Id").then(( res ) => {
setBillIdFetch(res.data[0].Bill_Id + 1);
});
}, []);
useEffect(() => {
if (billIdFetch === undefined) return;
setProduct_Details([{
index: Math.random(),
billId : BillIdFetch,
prodId: "",
qty: "",
price: "",
prod_SrNo: "",
discount_price: "",
proData_warranty: "",
}])
}, [billIdFetch])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.