简体   繁体   中英

forEach not working for response.data in React

I am trying to loop through a response from a data file however, I am getting an error I can't debug or see why it doesn't work. I had tried the forEach and map within a function but it failed just the same.

I had tried the forEach and map within a function but it failed just the same.

class GetTiles extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tileData: {},
            dataLoaded: false
        };
    }

    loadData() {
        axios("assets/data/home.json")
            .then(response => {
                this.setState({
                    tileData: response.data.titles,
                    dataLoaded: true
                });
                console.log("Local Tiles Ajax Call: Success");
            })
            .catch(err => {
                console.log("Local Tiles Ajax Call", err);
            });
    }

    componentDidMount() {
        this.loadData();
    }

    render() {
        return (
            <>
                <Tile title="1" />
                {this.state.tileData.map((item, index) => (
                    <p key={index}>Hello!</p>
                ))}
            </>
        );
    }
}

export default GetTiles;

Please note I know it doesn't make sense why I am doing this, but it is to help me understand and debug the issue/Get something working.

{
    "_id": "home",
    "titles": [
        {
            "type": "app",
            "title": [
                {
                    "text": "Demo",
                    "locale": "en-gb"
                }
            ],
            "data": {
                "app_name": "lorem",
                "category": "demo"
            }
        },
        {
            "type": "app",
            "title": [
                {
                    "text": "Demo 2",
                    "locale": "en-gb"
                }
            ],
            "data": {
                "app_name": "ipsum",
                "category": "sports"
            }
        }
    ]
}

I am wanting to be able to target titles within the JSON to get data from it and print out data for each onto the page.

The Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See *** for more information.

Your initial state tileData is an object. You can't forEach or map over an object but that's what you've asked the code to do. It will try to iterate over that state property on the first render which is probably what that error is.

Change

this.state = { tileData: {} }

to

this.state = { tileData: [] }

and then add a condition to your render to return something else if the array is empty, something like:

render() {
  if (!this.state.titleData.length) return <div>No data</div>
  return this.state.tileData.map(tile => etc
}

First of all you have to change this.state = {tileData: {}, ...} to this.state = {tileData: [],...} .

Your first lines should look like:

constructor(props) {
super(props);
this.state = { tileData: [], dataLoaded: false };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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