首页 > 解决方案 > 渲染的反应格式——语法——意外标记

问题描述

我想知道为什么我的 React 类的格式是错误的?它说应该有一个括号,但我确实包括了一个括号?不过,我可能忘记了语法格式的某些方面:(这是我的 js 文件中的一个片段:

function App() {
  state = {
    posts = []; 
    input = '';
  };
  componentDidMount = () => {
    this.getPosts();
  };
  getPosts = () => {
    axios.get('(server)')
    // replace (server) with server link
      .then((response) => {
        const data = response.data;
        this.setState({ posts: data });
      })
  }
  displayBlogPost = (posts) => {
    if (!posts.length) return null;
    return posts.map((post, index) => (
      <div key={index} className="post__display">
        <h3>"name " + post.name </h3>
        <h3>"City " + post.location </h3>
        <h3>"Requesting " + post.type </h3>
        <h3> post.message </h3> 
      </div>
    ));
  };

  render() {
      return (
        <div className="App">
        <header> 
            <h2> Covunity </h2> 
            <SearchExample items= { this.state.posts } />
        </header>
            </div>
        <div className="gallery"> 
        {this.displayBlogPost(this.state.posts)} </div> 
    )
    document.getElementById('root')
  }
}

错误信息是

Syntax error: Unexpected token, expected ";" (54:12) 

(在渲染())

标签: reactjserror-handlingsyntaxfrontend

解决方案


首先,您必须返回单个元素。相反,您返回 2。然后,渲染方法实现中的最后一行是无法访问的(在返回之后)。尝试这个:

render() {
  return (
    <div>
      <div className="App">
        <header>
          <h2> Covunity </h2>
          <SearchExample items={this.state.posts}/>
        </header>
      </div>
      <div className="gallery">
        {this.displayBlogPost(this.state.posts)}
      </div>
    </div>
  )
  // document.getElementById('root')
}

推荐阅读