猿问

无法更正 Unexpected token, expected ":" in reactjs 的错误

我的状态变量包含一个对象数组(其中每个对象都包含用户名、user_DP、imageUrl、标题),这些对象将被渲染,但是在使用 map() 渲染时会出现一个我无法解决的错误。


状态变量的例子:


this.state = {

      route: 'signin',

      postDetails: [...]

    };

我的 render() 看起来像


render(){

    const {route, postDetails} = this.state;

    return (

      <div className="App">

      {

        route === 'home' ?

          <Navbar/>

            {

              postDetails.map((post,index)=>{

                return(<Post 

                        key = {index} 

                        username = {post.username} 

                        user_DP = {post.user_DP}

                        imageUrl = {post.imageUrl}

                        caption = {post.caption}

                      />);      

              })

            }

          :

          (

            route === 'signin'?

              <Signin onRouteChange = {this.onRouteChange}/>

              :

              <Signup onRouteChange = {this.onRouteChange}/>

          )

      }

      </div>

    );

  }

我收到这样的错误


Syntax error: Unexpected token, expected ":" (44:13)


  42 |         route === 'home' ?

  43 |           <Navbar/>

> 44 |             {

     |             ^

  45 |               postDetails.map((post,index)=>{

  46 |                 return(<Post 

  47 |                         key = {index}

请帮助消除此错误,这将对我有很大帮助。


白猪掌柜的
浏览 173回答 1
1回答

斯蒂芬大帝

您的<Navbar />和map()with&nbsp;<Post>s 必须在单个节点内。您可以在不破坏您的设计的情况下使用React.Fragment或包装它们:<div>React.Fragment 组件允许您在 render() 方法中返回多个元素,而无需创建额外的 DOM 元素。function render() {&nbsp; const { route, postDetails } = this.state;&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; {route === "home" ? (&nbsp; &nbsp; &nbsp; &nbsp; <> {/* <- shorthand for <React.Fragment> */}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Navbar />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {postDetails.map((post, index) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Post&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key={index}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username={post.username}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; user_DP={post.user_DP}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; imageUrl={post.imageUrl}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; caption={post.caption}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })}&nbsp; &nbsp; &nbsp; &nbsp; </> {/* <- shorthand for </React.Fragment> */}&nbsp; &nbsp; &nbsp; ) : route === "signin" ? (&nbsp; &nbsp; &nbsp; &nbsp; <Signin onRouteChange={this.onRouteChange} />&nbsp; &nbsp; &nbsp; ) : (&nbsp; &nbsp; &nbsp; &nbsp; <Signup onRouteChange={this.onRouteChange} />&nbsp; &nbsp; &nbsp; )}&nbsp; &nbsp; </div>&nbsp; );}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答