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

Material UI AutoComplete城市选择后无法联动加载关联社区数据

问题分析与修复方案

你的代码存在三个关键问题导致联动功能失效:

1. API请求参数错误

选择城市后,selectedCity是一个包含City属性的对象,但你直接把它拼接到URL中,导致请求变成http://localhost:3031/cities?City=[object Object],后端无法识别这个参数。需要用selectedCity.City来传递城市名称。

2. 第二个AutoComplete的选项标签错误

第二个组件用于选择社区,但你设置getOptionLabel={society => society.City},这会把每个社区的城市名显示出来,而非社区自身的名称。需要替换成社区对应的字段(比如society.Society或society.Municipality,根据你的API返回结构调整)。

3. 未清理旧数据(可选优化)

切换城市时,先清空之前的社区列表,避免旧数据残留影响用户体验。


修正后的代码

import { React, useState, useEffect } from 'react';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';

function AutocompleteDropdown() {
  const [cities, setCities] = useState([]);
  const [selectedCity, setSelectedCity] = useState(null);
  const [societies, setSocieties] = useState([]);

  useEffect(() => {
    // 获取城市列表
    fetch('http://localhost:3031/cities')
      .then(response => response.json())
      .then(data => setCities(data))
      .catch(error => console.error('获取城市列表失败:', error));
  }, []);

  useEffect(() => {
    if (selectedCity) {
      // 切换城市时先清空社区列表
      setSocieties([]);
      // 传递城市名称作为参数,而非整个对象
      fetch(`http://localhost:3031/cities?City=${selectedCity.City}`)
        .then(response => response.json())
        .then(data => setSocieties(data))
        .catch(error => console.error('获取社区列表失败:', error));
    }
  }, [selectedCity]);

  return (
    <div>
      <Autocomplete
        options={cities}
        getOptionLabel={city => city.City}
        onChange={(_, newValue) => setSelectedCity(newValue)}
        renderInput={params => <TextField {...params} label="选择城市" />}
      />
      {selectedCity && (
        <Autocomplete
          options={societies}
          // 替换为社区的名称字段,比如Society或Municipality
          getOptionLabel={society => society.Society || '无社区名称'}
          renderInput={params => <TextField {...params} label="选择社区" />}
        />
      )}
    </div>
  );
}

export default AutocompleteDropdown;

额外检查建议

  • 确认后端APIhttp://localhost:3031/cities?City=XXX确实返回对应城市的社区列表,且每个社区对象包含正确的名称字段(比如Society)。
  • 在浏览器控制台查看Network请求,确认请求URL是否正确,后端返回的数据结构是否符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 02:20:18