简体   繁体   English

forEach 不适用于 React 中的 response.data

[英]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.我曾在 function 中尝试过 forEach 和 map 但同样失败了。

I had tried the forEach and map within a function but it failed just the same.我曾在 function 中尝试过 forEach 和 map 但同样失败了。

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.我希望能够定位 JSON 中的标题以从中获取数据并将每个标题的数据打印到页面上。

The Error: A cross-origin error was thrown.错误:引发了跨域错误。 React doesn't have access to the actual error object in development. React 无法访问开发中的实际错误 object。 See *** for more information.有关详细信息,请参阅 ***。

Your initial state tileData is an object.您最初的 state tileData是 object。 You can't forEach or map over an object but that's what you've asked the code to do.您不能forEachmap超过 object 但这就是您要求代码执行的操作。 It will try to iterate over that state property on the first render which is probably what that error is.它将尝试在第一次渲染时迭代 state 属性,这可能就是那个错误。

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: [],...} .首先,您必须将this.state = {tileData: {}, ...}更改为this.state = {tileData: [],...}

Your first lines should look like:您的第一行应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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