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

react-select三级联动选择器第三级选中值无法正常渲染如何解决

问题原因
  • 第三个Select组件仅配置了getOptionLabel,缺少getOptionValue配置:react-select默认通过option.value匹配选中值,而你的第三个下拉的options是纯字符串数组,不存在value属性,导致组件无法识别选中项,因此无法渲染选中内容。
  • 现有useEffect属于完全冗余的无效代码:在useEffect中根据title变化重新setTitle,没有任何业务作用,可直接删除。
  • 状态重置逻辑不完整:切换产品、类型时未同步清空下游的标题状态,可能出现旧选中值和新选项列表不匹配的异常。
修复方案
  1. 给第三个Select添加getOptionValue配置,直接返回字符串本身作为匹配值
  2. 删除冗余的useEffect代码
  3. 补充状态清空逻辑,切换上游选项时同步清空所有下游关联状态
修正后的完整代码
import React, { useState } from "react";
import Select from "react-select";
import data from "../data.json";

const Dropdowns = () => {
  const [product, setProduct] = useState(null);
  const [type, setType] = useState(null);
  const [typesList, setTypesList] = useState(null);
  const [title, setTitle] = useState(null);
  const [titlesList, setTitlesList] = useState(null);

  // 产品下拉变更处理
  const handleProductChange = (obj) => {
    setProduct(obj);
    setTypesList(obj.types);
    // 清空下游所有关联状态
    setType(null);
    setTitlesList(null);
    setTitle(null);
  };

  // 类型下拉变更处理
  const handleTypesChange = (obj) => {
    setType(obj);
    setTitlesList(obj.titles);
    // 清空下游标题状态
    setTitle(null);
  };

  // 标题下拉变更处理
  const handleTitlesChange = (obj) => {
    setTitle(obj);
  };

  return (
    <>
      <br />
      <h3>Products</h3>
      <Select
        placeholder="Select Product"
        value={product}
        options={data}
        onChange={handleProductChange}
        getOptionLabel={(x) => x.product}
        getOptionValue={(x) => x.product}
      />
      <br />
      <h3>Types</h3>
      <Select
        placeholder="Select Types"
        value={type}
        options={typesList}
        onChange={handleTypesChange}
        getOptionLabel={(x) => x.type}
        getOptionValue={(x) => x.type}
      />
      <br />
      <h3>Titles</h3>
      <Select
        placeholder="Select Title"
        value={title}
        options={titlesList}
        onChange={handleTitlesChange}
        getOptionLabel={(x) => x}
        getOptionValue={(x) => x}
      />
    </>
  );
};

export default Dropdowns;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:18:00