You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MaterialUI Select下拉框中从父对象渲染子对象选项

问题原因

你的代码核心问题是两处遗漏return语句,以及key属性重复:

  • 第一层this.state.data.map的匹配分支中,你没有将dt.link.map的执行结果返回,导致外层map拿到的是undefined
  • 内层dt.link.map的迭代逻辑没有return语句,生成的MenuItem无法被外层接收
  • 所有MenuItem共用外层循环的索引i作为key,同一location下的多个摄像头选项key重复,会导致React列表渲染异常

修正后的代码

import React from "react";
import { Select, MenuItem, FormControl, InputLabel } from "@material-ui/core";
import "./CamSelect.css"

export default class CamSelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        currentLocation: localStorage.getItem("location") || "abc", // 新增兜底值方便测试
        data: [
            {
                location: "abc",
                link: [
                    {name: "cam1", url: "https://...."},
                    {name: "cam2", url: "https://...."}
                ]
            },
            {
                location: "xyz",
                link: [
                  {name: "cam1", url: "https://...."},
                ]
            },
        ],
        selected: '',
    };
  }

  handleChange = (event) => {
    this.setState({ selected: event.target.value, name: event.target.name });
  };

  renderOptions() {
    return this.state.data.map((dt, i) => {
      if(this.state.currentLocation === dt.location){
        // 新增return返回内层map的结果
        return dt.link.map((lnk, idx) => {
          console.log(lnk.name)
          return (
              <MenuItem
                  label="Select a camera"
                  value={lnk.url}
                  key={`${i}-${idx}`} // 修改为唯一key避免重复
                  name={lnk.name}
              >
                  {lnk.name}
              </MenuItem>
          )
        })
      }
      // 不匹配的location直接返回null
      return null
    })
  };
    
  render() {
    return (
      <FormControl className="camera-select" style={{ minWidth: "100px"}}>
        <InputLabel id="demo-simple-select-label" style={{color:"white"}}>Cam</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          className="camera-text-color"
          value={this.state.selected}
          onChange={this.handleChange}
        >
          {this.renderOptions()}
        </Select>
      </FormControl>
    );
  }
}

验证说明

修正后如果localStorage中location存储的值为abc,下拉框会自动展示cam1、cam2两个选项,选中后可以正常拿到对应的url作为value值。

内容的提问来源于stack exchange,提问作者Vishal K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 17:18:03