[英]A cross-origin error: occurring when setting Local-storage/React.State in ReactJS Hooks
I am facing an issue having Error of A cross-origin error
, I am simply receiving the array of objects from child(Basket)
which I am looking to save in localstorage
& state
, but as soon as I write the code to save the application breaks and showing the below error, point to note that I am also saving the state and localstorage
for other items but it's not broken only when I write the below code in my application to save in localstorageuser-final
and state finalBuy
Any suggestions please guys.我遇到了
A cross-origin error
错误错误的问题,我只是从child(Basket)
接收对象数组,我希望将其保存在localstorage
和state
中,但是一旦我编写代码来保存应用程序中断并显示以下错误,请注意我还在为其他项目保存 state 和localstorage
,但只有当我在我的应用程序中编写以下代码以保存在localstorageuser-final
和 state finalBuy
任何建议时,它才不会损坏。
Main (APP)___|
|_Child 1(Signin)
|_Child 2 (Basket)
If I exclude this below section of code the rest of application works fine
.如果我排除以下代码部分,则应用程序的 rest
works fine
。
let finalbuyitems = () => {
let z1 = JSON.parse(window.localStorage.getItem("user-final") || "[]");
console.log(z1);
return z1;
};
const [finalBuy, setfinalBuy] = useState(finalbuyitems());
// also i add resetBasket and set the setfinalBuy as well
const resetBasket = (basketItems) => {
setfinalBuy([...basketItems]);
window.localStorage.setItem("user-final", JSON.stringify([...basketItems]));
setBasketItems([]);
window.localStorage.setItem("user-basket", []);
};
I have console the finalbuyitems
but it is returning the whole function not sure why我有控制台
finalbuyitems
但它返回整个 function 不知道为什么
console.log(finalbuyitems);`
Below Snippet of all code from the App.js
下面是来自
App.js
的所有代码片段
import React, { useState, useEffect } from "react";
import logo from "./logo.svg";
import "./App.css";
import Nav from "./Nav";
import Sidebar from "./Component/Sidebar";
import Basket from "./Component/Basket";
import Accessories from "./Component/Accessories";
import Signin from "./Component/Signin";
import Error from "./Error";
import Home from "./Component/Home";
import Footer from "./Component/Footer";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
const userAccountData = () => {
return window.localStorage.getItem("user-data");
};
const isLoggedIn = () => {
return !!window.localStorage.getItem("user-status"); // !! : cast to boolean
};
let initialvalue = () => {
let y1 = JSON.parse(window.localStorage.getItem("user-basket") || "[]");
console.log(y1);
return y1;
};
// after i add finalbuyitems here i start getting the error
let finalbuyitems = () => {
let z1 = JSON.parse(window.localStorage.getItem("user-final") || "[]");
console.log(z1);
return z1;
};
console.log(finalbuyitems); //console to check the finalbuyitems
function App() {
const [siginalready, setifsignedin] = useState(isLoggedIn());
const [userData, setUserData] = useState(userAccountData());
const [basketItems, setBasketItems] = useState(initialvalue());
const [finalBuy, setfinalBuy] = useState(finalbuyitems());
// also i add resetBasket and set the setfinalBuy as well
const resetBasket = (basketItems) => {
setfinalBuy([...basketItems]);
window.localStorage.setItem("user-final", JSON.stringify([...basketItems]));
setBasketItems([]);
window.localStorage.setItem("user-basket", []);
};
const updatedBasket = (newProductQty) => {
setBasketItems((prevItems) => {
let updatedQuantityArray = [];
for (let z = 0; z < basketItems.length; z++) {
if (newProductQty.producNumber !== basketItems[z].producNumber) {
updatedQuantityArray.push(basketItems[z]);
} else {
if (newProductQty.quantity == 0) {
} else {
updatedQuantityArray.push(newProductQty);
}
}
}
window.localStorage.setItem("user-basket", JSON.stringify(updatedQuantityArray));
return updatedQuantityArray;
});
};
const addBasketitems = (product, quantity) => {
setBasketItems((prevItems) => {
let newItemsArray = [];
let changeHappen = 0;
if (basketItems.length < 1) {
const newItems = [...prevItems, { ...product, quantity }];
window.localStorage.setItem("user-basket", JSON.stringify(newItems));
return newItems;
} else {
const compareItem = [{ ...product, quantity }];
for (let i = 0; i < basketItems.length; i++) {
if (compareItem[0].producNumber !== basketItems[i].producNumber) {
newItemsArray.push(basketItems[i]);
} else {
newItemsArray.unshift(basketItems[i]);
newItemsArray[0].quantity = +basketItems[i].quantity + quantity;
changeHappen = 1;
}
}
if (changeHappen == 0) {
newItemsArray = [...newItemsArray, { ...product, quantity }];
}
console.log(newItemsArray);
window.localStorage.setItem("user-basket", JSON.stringify(newItemsArray));
return newItemsArray;
}
});
console.log(typeof product);
console.log("product", product);
// console.log(typeof quantity);
console.log("quantity", quantity);
};
console.log(typeof basketItems);
console.log(basketItems);
let url = "http://localhost:5000/api/verifyifloginalready";
let options = {
credentials: "include",
method: "POST",
};
let verifyifloginalready = new Request(url, options);
useEffect(() => {
credentailverify();
}, []);
function credentailverify() {
(async () => {
const x1 = await fetch(verifyifloginalready)
.then((res) => {
if (res.status == 400 || res.status == 401) {
console.log(res.status);
window.localStorage.removeItem("user-data");
return setifsignedin(false);
} else if (siginalready == false) {
setifsignedin(true);
return res.json();
} else {
return;
}
})
.then((data) => {
setUserData(data.data);
window.localStorage.setItem("user-status", true);
window.localStorage.setItem("user-data", data.data);
})
.catch((err) => console.log("err"));
console.log(userData);
console.log(siginalready);
return x1;
})();
}
return (
<Router>
<div className="App">
<header className="header">
<Nav userinfo={userData} userstatus={siginalready} />
</header>
<div className="main">
<Switch>
<Route path="/" exact render={(props) => <Home {...props} userData={userData} userstatus={siginalready} addBasketitems={addBasketitems} />} />
<Route
path="/basket"
exact
render={(props) => (
<Basket {...props} userData={userData} userstatus={siginalready} basketItems={basketItems} updatedBasket={updatedBasket} resetBasket={resetBasket} />
)}
/>
<Route path="/signin" exact render={(props) => <Signin {...props} userData={userData} finalBuy={finalBuy} userstatus={siginalready} />} />
<Route path="/accessories" exact render={(props) => <Accessories {...props} userData={userData} userstatus={siginalready} />} />
</Switch>
</div>
<div className="footer">
<Footer />
</div>
</div>
</Router>
);
}
export default App;
Snippet from the Basket.js
来自
Basket.js
的片段
when the button is clicked it will call the buyNow function and send the basketItems
from child
to Parent(APP)
单击按钮时,它将调用 buyNow
basketItems
并将购物篮项目从child
发送到Parent(APP)
const buyNow = (basketItems) => {
resetBasket(basketItems);
window.location.href = "http://localhost:3000/signin";
};
Hi Umair_007 it's been 9 months without an answer.嗨 Umair_007 已经 9 个月没有答案了。
I have two suggestions:我有两个建议:
Firstly, your code examples are two lengthy for others to study them and devise a coherent answer, and首先,您的代码示例对于其他人来说是两个冗长的研究,而 devise 是一个连贯的答案,并且
Secondly, when instead of the data JS returns the function that should proide the date, chances are that a pair of parenthesis is missing in the code, you know, the difference between referencing a function vs. calling it.其次,当 JS 返回 function 而不是数据时,应该提供日期,很可能代码中缺少一对括号,你知道,引用 function 与调用它之间的区别。 But this is just a guess.
但这只是一个猜测。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.