【问题标题】:React conditional rendering - Why doesn't this code render anything?React 条件渲染 - 为什么这段代码不渲染任何东西?
【发布时间】:2020-07-20 20:00:34
【问题描述】:

我有一个面板,它应该根据它通过道具获得的查询类型呈现选项列表。查询类型可以识别,但它应该映射到状态并呈现元素列表。但它根本没有渲染任何东西。这是为什么?谢谢!

export default class SortSearchFilterPanel extends Component {
  constructor(props) {
    super(props);
    this.type = this.props.type;
    this.state = {
      sortList: [
        "What's New",
        "Name A-Z",
        "Name Z-A",
        "ABV Low To High",
        "ABV High To Low",
        "Price Low To High",
        "Price High To Low"
      ],
      filterList: ["Filter By Name", "Filter By Price"]
    };
  }

  render() {
    const { type } = this.props.type;
    const { sortList, filterList } = this.state;
    switch (type) {
      case "search":
        return (
          <div className="PanelGrid">
            <input type="text" name="serch" placeholder="Search..." />
          </div>
        );
        break;
      case "sort":
        return (
          <div className="PanelGrid">
            <ul className="PanelList">{sortList.map(item => <li key={item}>item</li>)}
            </ul>
          </div>
        );
        break;
      case "filter":
        return (
          <div className="PanelGrid">
            <ul className="PanelList">
              {filterList.map(item => <li key={item}>item</li>)}
            </ul>
          </div>
        );
        break;
      default:
        return null;
        break;
    }
  }
}

【问题讨论】:

  • 尝试在 switch case 中调试 type 值是否即将到来?
  • 你至少得到&lt;div className="PanelGrid"&gt;吗?

标签: reactjs switch-statement conditional-statements rendering


【解决方案1】:

我相信你的问题出在类型 prop 的声明中:

你有这个:

const { type } = this.props.type;

应该是这样的:

const { type } = this.props;

【讨论】:

  • 很好看!我猜是典型的菜鸟错误...感谢您的快速修复。
猜你喜欢
  • 2016-06-21
  • 2019-03-21
  • 1970-01-01
  • 2017-10-06
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 2017-10-08
相关资源
最近更新 更多