Antd 选择搜索框不呈现匹配项

IT技术 javascript reactjs antd react-select-search
2021-05-02 23:50:46

我有产品数据,我正在使用搜索值过滤数据,然后使用过滤后的数据呈现选项。产品数据来自全球 redux 商店作为props。出于某种原因,下拉列表仅在搜索值为空时显示数据,当我开始输入时,filteredData更新并重新渲染组件,但选项不显示数据。

我已经检查了是否使用权限filteredData来映射选项。即使重新渲染组件,这些选项似乎也不会渲染。

请看下面的代码:

import React from 'react';
// import {useState} from 'react';
import {Select} from 'antd';
import {connect} from 'react-redux';
import {fetchProductsAsync} from 'common/actions/fetchData';

const {Option} = Select;

class SelectOptions extends React.Component {
  state = {
    filteredData: [],
    value: undefined,
  };

  componentDidMount() {
    const {fetchProductsAsync} = this.props;
    fetchProductsAsync();
    const {products} = this.props;
    this.setState({filteredData: products || []});
  }

  componentDidUpdate() {
    console.log(this.state.filteredData);
  }

  filterData = (value) => {
    const {products} = this.props;
    const filData = products.filter((prod) => {
      return prod.name.includes(value);
    });
    // console.log(filData);
    this.setState({filteredData: filData});
  };

  handleSearch = (value) => {
    const {products} = this.props;
    if (value) {
      // this.setState({value});
      this.filterData(value);
      // console.log('yes');
    } else {
      console.log('empty');
      this.setState({filteredData: products});
      this.forceUpdate();
    }
  };

  handleChange = (value) => {
    // console.log(value);
    this.setState({value});
  };
  render() {
    const {others} = this.props;
    // console.log(this.state.filteredData);
    const options = this.state.filteredData.map((item, index) => {
      console.log(item);
      return (
        <Option value={item.value || item[others.key] || item}>
          {others.customTitle ? (
            <text style={{fontSize: 13, fontWeight: 'bold'}}>{item[others.customTitle]}</text>
          ) : (
            item.label || item[others.key] || item
          )}
          {others.dataKeys ? (
            <div className="row" style={{flexWrap: 'wrap'}}>
              {others.dataKeys.map((i) => (
                <text style={{fontSize: 11, marginLeft: 5, marginRight: 5}}>{item[i]}</text>
              ))}
            </div>
          ) : null}
        </Option>
      );
    });
    return (
      <Select
        showSearch
        onSearch={this.handleSearch}
        // placeholder="Select"
        // key={this.state.filteredData.length}
        value={this.state.value}
        onChange={this.handleChange}>
        {options}
      </Select>
    );
  }
}

const mapStateToProps = (state) => {
  return {products: state.data.products || []};
};

export default connect(mapStateToProps, {fetchProductsAsync})(SelectOptions);
1个回答

尝试在 Select 组件上设置此props filterOption={false}