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

Antd Autocomplete列表缺失key问题排查求助

Antd Autocomplete 缺失Key问题修复方案

问题分析

你的代码存在三个核心问题导致Key缺失提示:

  1. 选项结构错误:Antd AutoComplete的options数组要求每个元素包含value字段(用于显示和选中值),你错误地使用了options字段;同时用index作为key不够可靠,订单ID本身是唯一值,更适合作为key。
  2. 变量覆盖与搜索逻辑错误:render函数中重新定义的options变量覆盖了state中的同名变量,且handleSearch直接将用户输入作为选项,而非从已有的订单ID中过滤匹配项。
  3. 空数据处理缺失:当接口返回无数据时,data会被设为null,此时执行data.map会报错。

修复步骤及代码

以下是修复后的完整代码:

class OrdersPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            options: [],
            loading: true, // 初始化loading状态
            errorMessage: ''
        };
        this.handleSearch = this.handleSearch.bind(this);
        this.onSelect = this.onSelect.bind(this);    
    }
   

    componentDidMount() {
        API.get(`orders`,{ headers: { Authorization: this.token}})
            .then(res => {
                if(!Object.keys(res.data).length){
                    console.log("no data found");
                    this.setState({loading: false, data: [] }); // 设为空数组而非null,避免map报错
                }
                else
                {
                    const orders = res.data._embedded.ordersDtoList;
                    this.setState({loading: false, data: orders });
                }
            })
            .catch(error => {
                const message = JSON.stringify(error.response.data.error_message);
                if(message.includes("The Token has expired")){
                    this.setState({errorMessage:"Your token has expired", loading: false})
                }
                else{
                    this.setState({errorMessage: error.message, loading: false})
                }
                this.errorHappend("Failed to load data");
                console.error('There was an error!', error);
        });
    }

    onSelect = (value) => {
        console.log('onSelect', value);
    };
    
    handleSearch = (value) => {
        const { data } = this.state;
        // 根据输入值过滤订单ID,生成符合要求的选项
        const filteredOptions = value 
            ? data.map(item => ({
                key: item.id.toString(),
                value: item.id.toString()
            })).filter(opt => opt.value.includes(value))
            : [];
        this.setState({ options: filteredOptions });
      }
 
    render() {
        const { data, loading, options, errorMessage } = this.state;

        return (
            <Layout>
                <Content>
                    {errorMessage && <div style={{color: 'red', marginBottom: '1em'}}>{errorMessage}</div>}
                    {loading ? (
                        <div>Loading...</div>
                    ) : (
                        <div style={{marginBottom:"1em"}}>
                            <AutoComplete 
                                style={{ width: 200 }}  
                                options={options} 
                                onSelect={this.onSelect} 
                                onSearch={this.handleSearch}
                            >
                                <Input.Search size="large" placeholder="Search order by id" enterButton />
                            </AutoComplete>
                        </div>
                    )}
                </Content>
            </Layout>
        );
    }
}

export default OrdersPage;

关键修复点说明

  • 选项结构修正:每个选项对象使用key: item.id.toString()和value: item.id.toString(),保证key的唯一性,同时符合Antd组件要求。
  • 搜索逻辑优化:handleSearch中根据用户输入过滤已有订单ID,生成匹配的选项列表,而非直接将输入作为选项。
  • 空数据处理:无数据时将data设为空数组,避免map报错;同时添加loading状态提示,提升用户体验。
  • 变量冲突解决:移除render中重新定义的options变量,直接使用state中维护的过滤后的选项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:15:31