[英]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.