【问题标题】:Why I am getting cross origin error in React?为什么我在 React 中遇到跨源错误?
【发布时间】:2020-11-09 15:36:47
【问题描述】:

我是 React 的新手。我已经构建了一个事件调度程序 Web 应用程序,但它只能在我的浏览器中运行,如果我在不同的浏览器或其他系统上尝试它会给我这个错误:

引发了跨域错误。 React 无法访问开发中的实际错误对象。

我试图弄清楚,但我能理解它正在发生,因为如果本地存储未定义,我会在状态中提供默认值。这里是my complete code

这是出现错误的组件:

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;

【问题讨论】:

    标签: javascript reactjs react-native local-storage


    【解决方案1】:

    您正在尝试parse 一个对象。 JSON.parse 需要 JSON,但您传递的是一个对象。

    您可以检查沙盒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
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-07
      • 2021-03-10
      • 2021-08-17
      • 1970-01-01
      • 2020-08-03
      • 2013-01-23
      相关资源
      最近更新 更多