如何解决React中的跨源错误?

问题描述

我使用React.js制作了一个简单的购物车。我正在使用localStorage存储状态值,以便即使刷新后,这些值仍保留在UI中。

此外,是否确实要通过状态修改Items内容,请更改 原始项目的内容?

以下是我用来渲染的不同文件:

ShoppingCart.js

import React,{ Component } from 'react';
import { Table,Button,Media,Card,CardHeader,CardBody,CardFooter } from 'reactstrap';
import Items from '../shared/Items';

class ShoppingCart extends Component {
    constructor(props) {
        super(props);

        this.state = {
            items: JSON.parse(localStorage.getItem("items")) || Items
        }
    }

    decreaseQuantity = (item) => {
        const copy = this.state.items;
        item.quantity -= 1;

        for(let i = 0; i < copy.length; i++) {
            if(copy[i].id === item.id)
                copy[i] = item;
        }

        localStorage.setItem("items",JSON.stringify(copy));

        this.setState({
            items: copy
        });
    };

    increaseQuantity = (item) => {
        const copy = this.state.items;
        item.quantity += 1;

        for(let i = 0; i < copy.length; i++) {
            if(copy[i].id === item.id)
                copy[i] = item;
        }

        localStorage.setItem("items",JSON.stringify(copy));

        this.setState({
            items: copy
        });
    };

    resetCart = () => {
        localStorage.setItem("items",JSON.stringify(Items));

        this.setState({
            items: Items
        })
    };

    removeItem = (item) => {
        let copy = this.state.items;

        copy.splice(copy.indexOf(item),1);

        localStorage.setItem("items",JSON.stringify(copy));

        this.setState({
            items: copy
        });
    }

    render() {
        const array = this.state.items;

        const total = array.reduce((acc,item) => acc + item.quantity,0);
        let typeDiscount = 0;
        let normalDiscount = 0;
        const totalPrice = array.reduce((acc,item) => {
            normalDiscount += ((item.quantity * item.price) * item.discount) / 100;

            if (item.type === "fiction")
                typeDiscount += ((item.quantity * item.price) * 15) / 100;
            
            return acc + (item.quantity * item.price);
        },0);

        const items = array.map((item) => (
            <tr key={item.id}>
                <td>
                    <Media>
                        <Media left className="mr-3">
                            <Media object data-src={item.img_url} style={{height: 20,width: 20}} placeholder={item.name} />
                        </Media>
                        <Media body>
                            {item.name}
                            <Button close onClick={() => this.removeItem(item)} />
                        </Media>
                    </Media>
                </td>
                <td>
                    <Button color="danger" className="mr-3" disabled={item.quantity === 1} 
                    onClick={() => this.decreaseQuantity(item)}>
                        -
                    </Button>
                    {item.quantity}
                    <Button color="success" className="ml-3" onClick={() => this.increaseQuantity(item)}>+</Button>
                </td>
                <td>{item.quantity * item.price}</td>
            </tr>
        ));

        

        return (
            <React.Fragment>
                <div className="container">
                    <div className="row">
                        <div className="col-md">
                        <Table>
                            <thead>
                                <tr>
                                    <th>Item({total})</th>
                                    <th>Qty</th>
                                    <th>Price</th>
                                </tr>
                            </thead>
                            <tbody>
                                {items}
                            </tbody>
                        </Table>
                        </div>
                        <div className="col-md">
                            <Card>
                                <CardHeader>Total</CardHeader>
                                <CardBody>
                                    <dl className="row p-1">
                                        <dt className="col-6">Items({total})</dt>
                                        <dd className="col-6">{totalPrice}</dd>
                                        <br />
                                        <dt className="col-6">Discount</dt>
                                        <dd className="col-6">{normalDiscount}</dd>
                                        <dt className="col-6">Type Discount</dt>
                                        <dd className="col-6">{typeDiscount}</dd>
                                    </dl>
                                </CardBody>
                                <CardFooter>
                                    <dl className="row p-1">
                                        <dt className="col-6">Order Total</dt>
                                        <dd className="col-6">{totalPrice - normalDiscount - typeDiscount}</dd>
                                    </dl>
                                </CardFooter>
                            </Card>
                        </div>
                    </div>
                </div>
                <br /><br />
                <Button style={{position: "absolute",right: 500}} color="primary" className="mt-5" onClick={this.resetCart}>Reset</Button>                
            </React.Fragment>
        );
    }
}

export default ShoppingCart;

App.js

import React from 'react';
import ShoppingCart from './components/ShoppingCart';

function App() {
  return (
    <div className="mt-5">
      <ShoppingCart />
    </div>
  );
}

export default App;

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,document.getElementById('root')
);

serviceWorker.unregister();

Items.js

//The JSON file containing the items data
const Items = [{ "id": 9090,"name": "Item1","price": 200,"discount": 10,"type": "fiction","img_url": "https://place-hold.it/40.jpg","quantity": 1 },{ "id": 9091,"name": "Item2","price": 250,"discount": 15,"type": "literature",{ "id": 9092,"name": "Item3","price": 320,"discount": 5,{ "id": 9093,"name": "Item4","price": 290,"discount": 0,"type": "thriller",{ "id": 9094,"name": "Item5","price": 500,"discount": 25,{ "id": 9095,"name": "Item6","price": 150,{ "id": 9096,"name": "Item7","price": 700,"discount": 22,{ "id": 9097,"name": "Item8","price": 350,"discount": 18,"quantity": 1 }];

export default Items;

我尝试运行该应用程序,但一直出现以下错误:

Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.

有人可以帮我吗?我在做什么错了?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)