[英]Why I am getting cross origin error in React?
I am quite new in React.我是 React 的新手。 I have build an event scheduler web app but it's only working in my browser if I try it to different browsers or someone else system it gives me this error:
我已经构建了一个事件调度程序 Web 应用程序,但它只能在我的浏览器中运行,如果我尝试将它用于不同的浏览器或其他系统,它会给我这个错误:
A cross-origin error was thrown.
抛出了跨域错误。 React doesn't have access to the actual error object in development.
React 无法访问开发中的实际错误对象。
I am trying to figure out but all I can understood it's happening because I am giving default values in state if local storage in undefined.我想弄清楚,但我只能理解它正在发生,因为如果本地存储未定义,我将在 state 中提供默认值。 Here is my complete code .
这是我的完整代码。
This is the component that is getting the error:这是出现错误的组件:
import React from "react";
import { Container, Row, Table } from "react-bootstrap";
import EventModal from "./EventModalButton";
class EventList extends React.Component {
constructor(props) {
super(props);
this.state = {
title: "",
eventtype: "",
time: ""
};
}
componentDidMount() {
const defaultData = {
title: "AI",
eventtype: "Workshop",
time: "02:00PM"
};
const eventData = JSON.parse(localStorage.getItem("Data") || defaultData);
this.setState({
title: eventData.title,
eventtype: eventData.eventtype,
time: eventData.time
});
}
render() {
return (
<Container fluid="md">
<Table striped bordered hover>
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>Time</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>{this.state.title}</td>
<td>{this.state.eventtype}</td>
<td>{this.state.time}</td>
<td>Monday, 31/08/2020</td>
</tr>
</tbody>
</Table>
<Container className="row" />
<Row className="justify-content-center">
<EventModal />
</Row>
</Container>
);
}
}
export default EventList;
You're trying to parse
an object.您正在尝试
parse
一个对象。 JSON.parse
expects a JSON but you're passing an object. JSON.parse
需要一个 JSON,但你传递的是一个对象。
You could check the sandbox here你可以在这里检查沙箱
componentDidMount() {
const defaultData = {
title: "AI",
eventtype: "Workshop",
time: "02:00PM"
};
// JSON.parse throws an error when parsing the object.
const eventData = JSON.parse(localStorage.getItem("Data")) || defaultData;
this.setState({
title: eventData.title,
eventtype: eventData.eventtype,
time: eventData.time
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.