繁体   English   中英

React Component问题(预期为“;”,但发现为“,”)

[英]React Component problem (';' expected, but found ',')

这真让我抓狂。 我刚刚开始尝试学习的反应,但是由于一个非常奇怪的错误,我什至无法进行简单的API调用。

这是我的代码->

import React, {Component} from 'react';

class ApiPosts extends Component {
    constructor() {
        super();
        this.state = {
            blogPosts: [],
        };
    }
}

componentDidMount(){

    fetch('http://localhost:53595/blog/posts')
    .then(results => {
        return results.json();
    }).then(data => {
        let blogPosts = data.results.map((post) => {
            return(
                <div key={post.results}>
                    <div>{post.body}</div>
                </div>
            )
        });
        this.setState({blogPosts: blogPosts});
        console.log("state", this.state.blogPosts);
    })
}

render(){
    return (
        <div className="container2">
            <div className="container1">
                {this.state.blogPosts}
            </div>
        </div>
    )
}

第12行和第30行(“ componentDidMount(){和render(){”)向我抛出一个错误,表明我没有用';'将其关闭。

该错误显示在Visual Studio代码中,并且无法构建我的应用,并出现以下错误->

/react-website/src/ApiPosts.js: Unexpected token, expected ; (12:19)

我确实试图关闭该文件中的所有内容,只是为了查看错误的出处,但没有运气。

任何想法?

在您的组件类中移动componentDidMount和render函数。 在给定的代码片段中,它们不在类中。

import React, {Component} from 'react';

class ApiPosts extends Component {
    constructor() {
        super();
        this.state = {
            blogPosts: [],
        };
    }
    componentDidMount() {}
    render() {}
}

您具有componentDidMount并在组件本身之外定义了render

它看起来应该像这样:

import React, {Component} from 'react';

class ApiPosts extends Component {
    constructor() {
        super();
        this.state = {
            blogPosts: [],
        };
    }

    componentDidMount() {
       fetch('http://localhost:53595/blog/posts')
        .then(results => {
            return results.json();
        }).then(data => {
            let blogPosts = data.results.map((post) => {
                return(
                    <div key={post.results}>
                        <div>{post.body}</div>
                    </div>
                )
            });
            this.setState({blogPosts: blogPosts});
            console.log("state", this.state.blogPosts);
        })
    }

    render() {
        return (
            <div className="container2">
                <div className="container1">
                    {this.state.blogPosts}
                </div>
            </div>
        )
    }
}

暂无
暂无

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

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