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

React+MUI DataGrid中API数据无法在下拉选择框显示问题

问题分析与修复方案

你的代码存在三个核心问题,导致API获取的选项无法显示在下拉选择框中:

  • 未使用React状态管理数据:全局变量items更新时不会触发组件重新渲染,API请求完成后下拉框无法感知数据变化。
  • 错误拼接HTML字符串:直接将<option>xxx</option>格式的字符串插入JSX,React会将其视为纯文本而非DOM元素。
  • API请求触发时机错误:直接在组件函数内发起请求,会导致组件每次渲染都重复调用API,且无法保证组件挂载后数据才加载完成。

修复步骤

  1. 使用React状态存储选项数据
    用useState定义状态来保存API返回的选项,状态更新会自动触发组件重渲染。

  2. 通过JSX生成<option>元素
    遍历API返回的数据,直接创建React的<option>元素,而非拼接HTML字符串。

  3. 用useEffect执行API请求
    将API请求放在useEffect钩子中,确保仅在组件挂载时执行一次。

  4. 传递选项数据到编辑单元格组件
    将状态中的选项数据通过props传递给SelectEditInputCell组件,确保它能获取到最新的选项列表。

修复后的完整代码

import * as React from 'react';
import './style.css';
import Select, { SelectChangeEvent } from '@mui/material/Select';
import {
  DataGrid,
  GridRenderCellParams,
  GridColDef,
  useGridApiContext,
} from '@mui/x-data-grid';
import axios from 'axios';

// 定义评论数据类型
type Comment = {
  id: number;
  name: string;
};

function SelectEditInputCell(props: GridRenderCellParams & { options: Comment[] }) {
  const { id, value, field, options } = props;
  const apiRef = useGridApiContext();

  const handleChange = async (event: SelectChangeEvent) => {
    await apiRef.current.setEditCellValue({
      id,
      field,
      value: event.target.value,
    });
    apiRef.current.stopCellEditMode({ id, field });
  };

  return (
    <Select
      value={value}
      onChange={handleChange}
      size="small"
      sx={{ height: 1 }}
      native
      autoFocus
    >
      <option>Back-end Developer</option>
      <option>Front-end Developer</option>
      <option>UX Designer</option>
      {/* 遍历API数据生成option元素 */}
      {options.map(comment => (
        <option key={comment.id} value={comment.name}>
          {comment.name}
        </option>
      ))}
    </Select>
  );
}

export default function App() {
  const [options, setOptions] = React.useState<Comment[]>([]);

  // 组件挂载时仅执行一次API请求
  React.useEffect(() => {
    axios
      .get('https://jsonplaceholder.typicode.com/posts/1/comments')
      .then((response) => {
        setOptions(response.data);
      });
  }, []);

  // 依赖options动态生成列配置,确保选项更新时同步渲染
  const columns = React.useMemo<GridColDef[]>(() => [
    {
      field: 'name',
      headerName: 'Name',
      width: 120,
    },
    {
      field: 'role',
      headerName: 'Role',
      renderEditCell: (params) => <SelectEditInputCell {...params} options={options} />,
      editable: true,
      width: 180,
    },
  ], [options]);

  return (
    <div style={{ height: 300, width: '100%' }}>
      <DataGrid rows={rows} columns={columns} />
    </div>
  );
}

const rows = [
  {
    id: 1,
    name: 'Olivier',
    role: 'Back-end Developerrr',
  },
  {
    id: 2,
    name: 'Danail',
    role: 'UX Designerrrr',
  },
  {
    id: 3,
    name: 'Matheus',
    role: 'Front-end Developerrrr',
  },
];

关键说明

  • 用useState定义options状态,API请求完成后更新状态,触发组件重渲染。
  • 在SelectEditInputCell中直接遍历options生成<option>元素,确保React能正确解析为DOM节点。
  • 用useEffect包裹API请求,依赖项为空数组,确保仅在组件挂载时执行一次。
  • 通过useMemo定义columns,依赖options,确保选项更新时列的渲染逻辑同步更新。

内容的提问来源于stack exchange,提问作者HelloWorld1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 08:30:24