简体   繁体   中英

Syntactical error/jshint with in-line & map in ReactJS

here's my code, it is producing an "Expected an assignment or function call and instead saw an expression" error. I personally do not see any errors and my prettify works as usual. I believe it is the JSHINT that is calling me out here:

render() {
return (
  <div id="animalGallery">
    {this.props.displayData.map(eachProfilePic => {
      this.state.selected === eachProfilePic.iconID ? (
        <a
          class="animal selected"
          onClick={() => this.profilePicClick(eachProfilePic.iconID)}
        >
          <img src={eachProfilePic.iconID} />
        </a>
      ) : (
        <a
          class="animal"
          onClick={() => this.profilePicClick(eachProfilePic.iconID)}
        >
          <img src={eachProfilePic.iconID} />
        </a>
      );
    })}
  </div>
);}

It is calling that error on the fourth line in my code, does it appear to have any errors? If there isn't, is there another way I can write this code without triggering JSHINT?

You need to either add a return or remove the {} (or replace them with () ). When you use {} around a lambda, it expects a full function body, not just an expression to return.

Here's the correct code after adopting Joseph's answer: After removing the brackets:

render() {
return (
  <div id="animalGallery">
    {this.props.displayData.map(eachProfilePic =>
      this.state.selected === eachProfilePic.iconID ? (
        <a
          class="animal selected"
          onClick={() => this.profilePicClick(eachProfilePic.iconID)}
        >
          <img src={eachProfilePic.iconID} />
        </a>
      ) : (
        <a
          class="animal"
          onClick={() => this.profilePicClick(eachProfilePic.iconID)}
        >
          <img src={eachProfilePic.iconID} />
        </a>
      )
    )}
  </div>
);
}

Else, we can choose to add return instead:

render() {
return (
  <div id="animalGallery">
    {this.props.displayData.map(eachProfilePic => {
      return this.state.selected === eachProfilePic.iconID ? (
        <a
          class="animal selected"
          onClick={() => this.profilePicClick(eachProfilePic.iconID)}
        >
          <img src={eachProfilePic.iconID} />
        </a>
      ) : (
        <a
          class="animal"
          onClick={() => this.profilePicClick(eachProfilePic.iconID)}
        >
          <img src={eachProfilePic.iconID} />
        </a>
      );
    })}
  </div>
);
}

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