简体   繁体   中英

React not executing block of switch statement?

I have a product component that renders n number of sections. The code in the product component:

let sections = this.state.product.sections.map((section, idx) => {
  return (
    <Section sectionType={section.id} section={section} />
  )
})

return (
  <div>
    {this.state.product.name}
    {sections}
  </div>
)

The code in the section component:

renderSection() {
 switch (this.props.sectionType) {
  case 'heroImage':
    return (
      <img src={image.url} />
    )
  case 'doublePane':
    this.props.section.items.map((item, idx) => {
      console.log(item.id);
      if (1 === 1) {
        return (
          <div>hi</div>
        )
      }
    })
  default:
    return (
      <div>hey there</div>
    )
}
}

render() {
  return (
    <div>
      {this.renderSection()}
    </div>
)
}

I added the 1===1 line just to make sure it would execute, but the output of my code is still

  1. the heroImage case properly executes
  2. the console log of item.id happens (so we definitely enter the doublePane block), but the code inside of the 1===1 block does not execute.

Any idea what's happening here to not allow me to run the code inside of the 1===1? Thanks in advance!

You need to return the result of the mapping function, in addition to returning within the mapping function:

renderSection() {
  switch (this.props.sectionType) {
    case 'heroImage':
      return (
        <img src={image.url} />
      );
    case 'setOfTwo':
      return (
        <div>
          {this.props.section.items.map((item, idx) => {
             console.log(item.id);
             return (
               <div>hi</div>
             );
          })}
        </div>
      );
    default:
      return (
        <div>hey there</div>
      )
  }
}

Wrapping the return value in a div isn't necessarily required, but I prefer to return a consistent item (in this case a single JSX element) from functions.

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