![](/img/trans.png)
[英]A cross-origin error: occurring when setting Local-storage/React.State in ReactJS Hooks
[英]Updating a React state variable throws cross-origin error
目前我正在做一個項目,我想從我的 Python API 中獲取數據,更具體地說是字符串列表/數組,並使用 React 顯示該列表。 我得到了清單,它看起來完全沒問題。 沒有undefined
的值,一切都是String
並且它確實是Array
。 所以檢索到的數據似乎是有效的。 檢索數據后,我想在 React 中將其設置為 state 變量,以便我可以將其作為道具傳遞給另一個組件。
我正在使用pywebview作為我的 Python 應用程序的 React GUI。 JavaScript 模塊由 webpack 捆綁。
每當我調用setCourses()
時,我都會收到以下錯誤,並且 React 會顯示白屏。
錯誤:引發了跨域錯誤。 React 無法訪問開發中的實際錯誤 object。 有關詳細信息,請參閱https://reactjs.org/docs/cross-origin-errors.html 。
setCourses(["foo0", foo1", "foo2"]);
時不會拋出此錯誤。setCourses(new Array(response));
它不會拋出錯誤,而是以某種方式將 Arrays 元素連接到一個大小為 1 的新數組:["foo0", "foo1", "foo2"] -> ["foo0,foo1,foo2"]。cheap-module-source-map
設置提到的 React 錯誤頁面。 設置它也沒有幫助。 As you can see below, I am fetching the data from the Python API in a useEffect
hook and trying to set the state which shall rerender my component so that the child component <CourseList courses={courses} />
will display the courses.
export default function Dashboard(props) { // some props etc. were removed to keep this snippet simple // the state variable which causes issues const [courses, setCourses] = React.useState([]); // get Data from Python API React.useEffect(()=>{ getData(); }, []); /** * Gets the needed data (login status, courses, username) by calling the Python API */ function getData() { window.pywebview.api.foo().then((foo) => { // do stuff }).then(() => { // fetch the courses from the Python API window.pywebview.api.getCourses().then((response) => { // try to update the state variable setCourses(response); // <------- throws the error }).catch((response) => {console.log(response); }); } return ( <Box> <MainAppBar /> <Grid container spacing={0}> <Grid item> <MenuList /> </Grid> <Grid item> <CourseList courses={courses} /> {/* passing the courses to the CourseList component */} </Grid> <FloatingSyncButton /> </Grid> </Box> ) } export function CourseList({ courses }) { // logic... return ( <List> {/* trying to list each course item */} {courses.map((courseName) => { return ( <ListItem key={courseName} disablePadding > <ListItemButton> <Checkbox/> <ListItemAvatar> <Avatar>{courseName}</Avatar> </ListItemAvatar> <ListItemText primary={courseName} /> </ListItemButton> </ListItem> ); })} </List> ); }
我將不勝感激任何幫助。 謝謝!
你能試試這個嗎?
const getData = async () => {
try {
const api = await window.pywebview.api.foo()
// do some stuff with api
// fetch the courses from the Python API
const courseList = await window.pywebview.api.getCourses()
setCourses(courseList);
}
catch (e) {
console.log(error)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.