繁体   English   中英

更新 React state 变量会引发跨域错误

[英]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"]。
  • 遍历数组并构造一个新的 + 检查每个元素都是一个字符串
  • 在使用 webpack 的情况下,使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM