React不执行switch语句块?

问题描述 投票:0回答:1

我有一个产品组件,可以呈现n个部分。产品组件中的代码:

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

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

部分组件中的代码:

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>
)
}

我添加了1 === 1行只是为了确保它会执行,但我的代码的输出仍然是

  1. heroImage案例正确执行
  2. item.id的控制台日志发生(所以我们肯定会输入doublePane块),但是1 === 1块内的代码不会执行。

知道这里发生了什么,不允许我在1 === 1内部运行代码吗?提前致谢!

javascript reactjs
1个回答
0
投票

除了在映射函数中返回之外,还需要返回映射函数的结果:

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>
      )
  }
}

div中包含返回值不一定是必需的,但我更喜欢从函数返回一致的项(在本例中是单个JSX元素)。

© www.soinside.com 2019 - 2024. All rights reserved.