【问题标题】:Updating a React state variable throws cross-origin error更新 React 状态变量会引发跨域错误
【发布时间】:2021-12-31 13:17:28
【问题描述】:

上下文

目前我正在从事一个项目,我想从我的 Python API 获取数据,更具体地说是字符串列表/数组,并使用 React 显示该列表。 我得到了清单,它看起来完全没问题。没有undefined 值,一切都是String,它确实是Array。所以检索到的数据似乎是有效的。 检索数据后,我想将其设置为 React 中的状态变量,以便我可以将其作为道具传递给另一个组件。

我正在使用pywebview 作为我的 Python 应用程序的 React GUI。 JavaScript 模块被 webpack 打包。

错误

每当我调用 setCourses() 时,我都会收到以下错误,并且 React 会显示白屏。

错误:引发了跨域错误。 React 无权访问 开发中的实际错误对象。看 https://reactjs.org/docs/cross-origin-errors.html 了解更多 信息。

我注意到/尝试了什么

  • 调用setCourses(["foo0", foo1", "foo2"]); 时不会抛出此错误。
  • 当调用setCourses(new Array(response)); 时,它不会抛出错误,而是以某种方式将数组元素连接到一个大小为 1 的新数组:["foo0", "foo1", "foo2"] -> ["foo0,foo1 ,foo2"].
  • 遍历数组并构造一个新数组 + 检查每个元素都是字符串
  • 提到的error page of React 使用cheap-module-source-map 设置以防万一使用webpack。设置它也没有帮助。

类似的问题(没有解决我的问题)

简码sn-p

正如您在下面看到的,我在 useEffect 挂钩中从 Python API 获取数据,并尝试设置将重新呈现我的组件的状态,以便子组件 <CourseList courses={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>
    );
  }

我将不胜感激。谢谢!

【问题讨论】:

  • 当您尝试渲染课程时,课程似乎不存在。也许等待课程有有效数据。在 JSX 中试试这个 ``` {courses.length > 0 && } ``` 看看会发生什么。当您控制台记录响应时,是否有任何数据?
  • 感谢您的帮助!条件渲染并没有解决问题。是的,日志显示数据。
  • 你试过aysnc await而不是把.then嵌套在另一个.then里面吗?

标签: javascript reactjs pywebview


【解决方案1】:

你能试试这个吗?


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)
}
    }

【讨论】:

  • 刚试了一下...我成功获取数据但设置状态仍然会引发同样的错误。
猜你喜欢
  • 2018-11-10
  • 2018-05-03
  • 2017-10-15
  • 2021-02-19
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
相关资源
最近更新 更多