React-Select Async loadOptions未正确加载选项

Sha*_*kil 6 asynchronous reactjs react-async react-select

React Async Select loadoption有时无法加载该选项。在几个查询集合反应后,这是一个非常奇怪的现象。loadoptions未加载任何值,但我从日志中可以看到,结果正确地来自后端查询。我的代码库完全是最新的,请使用react-select新版本并使用

“反应选择”:“ ^ 2.1.1”

这是我的react-async select组件的前端代码。我确实在getOptions函数中使用了反跳,以减少后端搜索查询的数量。我猜这应该不会造成任何问题。我想补充一点,在这种情况下,我观​​察到的是,loadoptions serach指示器(...)也没有出现在这种现象中。

import React from 'react';
import AsyncSelect from 'react-select/lib/Async';
import Typography from '@material-ui/core/Typography';
import i18n from 'react-intl-universal';

const _ = require('lodash');

class SearchableSelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
      searchApiUrl: props.searchApiUrl,
      limit: props.limit,
      selectedOption: this.props.defaultValue
    };
    this.getOptions = _.debounce(this.getOptions.bind(this), 500);
    //this.getOptions = this.getOptions.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.noOptionsMessage = this.noOptionsMessage.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleChange(selectedOption) {
    this.setState({
      selectedOption: selectedOption
    });
    if (this.props.actionOnSelectedOption) {
      // this is for update action on selectedOption
      this.props.actionOnSelectedOption(selectedOption.value);
    }
  }

  handleInputChange(inputValue) {
    this.setState({ inputValue });
    return inputValue;
  }

  async getOptions(inputValue, callback) {
    console.log('in getOptions'); // never print
    if (!inputValue) {
      return callback([]);
    }
    const response = await fetch(
      `${this.state.searchApiUrl}?search=${inputValue}&limit=${
        this.state.limit
      }`
    );
    const json = await response.json();
    console.log('results', json.results); // never print
    return callback(json.results);
  }

  noOptionsMessage(props) {
    if (this.state.inputValue === '') {
      return (
        <Typography {...props.innerProps} align="center" variant="title">
          {i18n.get('app.commons.label.search')}
        </Typography>
      );
    }
    return (
      <Typography {...props.innerProps} align="center" variant="title">
        {i18n.get('app.commons.errors.emptySearchResult')}
      </Typography>
    );
  }
  getOptionValue = option => {
    return option.value || option.id;
  };

  getOptionLabel = option => {
    return option.label || option.name;
  };

  render() {
    const { defaultOptions, placeholder } = this.props;
    return (
      <AsyncSelect
        cacheOptions
        value={this.state.selectedOption}
        noOptionsMessage={this.noOptionsMessage}
        getOptionValue={this.getOptionValue}
        getOptionLabel={this.getOptionLabel}
        defaultOptions={defaultOptions}
        loadOptions={this.getOptions}
        placeholder={placeholder}
        onChange={this.handleChange}
      />
    );
  }
}

export default SearchableSelect;
Run Code Online (Sandbox Code Playgroud)

编辑以回应史蒂夫的答案

谢谢您的回答,史蒂夫。仍然没有运气。我会尝试根据您的回应来回应。

  1. 如果我不使用optionsValue,而是使用getOptionValue和getOptionLevel,那么查询结果将无法正确加载。我的意思是加载了空白选项,没有文本值。
  2. 是的,你是对的,是一个返回字符串的同步方法,我不需要重写它。并且此工作正常,并且noOptionsMessage正确显示。感谢指出这一点。
  3. actionOnSelectedOption不是noop方法,它可能要执行一些责任。我尝试将SearchableSelect用作独立组件,如果我需要一些后端操作来执行此功能,则会相应地触发该操作。例如,我在项目的用户配置文件中使用它,用户可以在其中从现有条目中更新他的学校/学院信息。当用户选择一个选项时,将执行配置文件更新责任。
  4. 是的,你是对的。谢谢,我不需要保持inputValue的状态。
  5. 我确保defaultOptions是一个数组。
  6. 我在不使用反跳的情况下进行测试,仍然没有运气。我正在使用去抖动来限制后端调用,否则对于我肯定不希望的每个按键都可能有一个后端调用。

异步选择可以完美地用于2/3查询,然后突然停止工作。我观察到一种明显的行为,即在这些情况下搜索指示符(...)也未显示。

非常感谢您抽出宝贵的时间。

编辑2以回应史蒂夫的答案

再次非常感谢您的回复。我对getOptionValue和getOptionLabel错误。如果loadOptions得到响应,则将调用这两个函数。所以我从以前的代码片段中删除了我的helper optionsValue函数,并根据(也在本帖子中)更新了我的代码片段。但是仍然没有运气。在某些情况下,异步选择无效。我尝试对这种情况进行截图。我在我的本地数据库名称“ tamim johnson”中确实使用了名称,但是当我搜索他时,我没有得到任何回应,但从后端得到了正确的回应。这是此案例的屏幕截图 塔米姆·约翰逊

我不确定此屏幕截图的清晰度如何。塔米姆·约翰逊(Tamim Johnson)在我的排名中也排名第六。

先生,谢谢您的时间。我不知道我在做什么错或错过了什么。

编辑3以回应史蒂夫的答案

这是名为“ tamim johnson”的用户搜索的预览选项卡响应。

预览标签

cra*_*tin 9

问题是 Lodash 的 debounce 功能不适合这个。Lodash 规定

对去抖动函数的后续调用返回最后一次 func 调用的结果

不是那个:

后续调用返回承诺,该承诺将解析为下一次 func 调用的结果

这意味着在等待期内对 debounced loadOptions prop 函数的每个调用实际上都在返回最后一个 func 调用,因此我们关心的“真实”承诺永远不会被订阅。

而是使用返回承诺的 debounce 函数

例如:

import debounce from "debounce-promise";

//...
this.getOptions = debounce(this.getOptions.bind(this), 500);
Run Code Online (Sandbox Code Playgroud)

查看完整解释https://github.com/JedWatson/react-select/issues/3075#issuecomment-450194917

  • 这一定是一个被接受的答案,因为它简单、优雅,并且真正解决了为什么 lodash 的 debounce 与 React-select 的异步不太适合。 (2认同)
  • 这就是我一直在寻找的解决方案。github 上的示例指定还应添加“leading:true”作为选项值。在我的情况下,这是不需要的。去掉之后就完美运行了。我有一个搜索字段,每次击键后都会触发 API 调用,这个承诺去抖现在仅在用户完成输入时触发。谢谢!:-) (2认同)

Ste*_*des 7

一些注释可以在代码下面找到。您正在寻找这样的东西:

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import AsyncSelect from 'react-select/lib/Async';
import debounce from 'lodash.debounce';
import noop from 'lodash.noop';
import i18n from 'myinternationalization';

const propTypes = {
  searchApiUrl: PropTypes.string.isRequired,
  limit: PropTypes.number,
  defaultValue: PropTypes.object,
  actionOnSelectedOption: PropTypes.func
};

const defaultProps = {
  limit: 25,
  defaultValue: null,
  actionOnSelectedOption: noop
};

export default class SearchableSelect extends Component {
  static propTypes = propTypes;
  static defaultProps = defaultProps;
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
      searchApiUrl: props.searchApiUrl,
      limit: props.limit,
      selectedOption: this.props.defaultValue,
      actionOnSelectedOption: props.actionOnSelectedOption
    };
    this.getOptions = debounce(this.getOptions.bind(this), 500);
    this.handleChange = this.handleChange.bind(this);
    this.noOptionsMessage = this.noOptionsMessage.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
  }

  getOptionValue = (option) => option.id;

  getOptionLabel = (option) => option.name;

  handleChange(selectedOption) {
    this.setState({
      selectedOption: selectedOption
    });
    // this is for update action on selectedOption
    this.state.actionOnSelectedOption(selectedOption.value);
  }

  async getOptions(inputValue) {
    if (!inputValue) {
      return [];
    }
    const response = await fetch(
      `${this.state.searchApiUrl}?search=${inputValue}&limit=${
      this.state.limit
      }`
    );
    const json = await response.json();
    return json.results;
  }

  handleInputChange(inputValue) {
    this.setState({ inputValue });
    return inputValue;
  }

  noOptionsMessage(inputValue) {
    if (this.props.options.length) return null;
    if (!inputValue) {
      return i18n.get('app.commons.label.search');
    }

    return i18n.get('app.commons.errors.emptySearchResult');
  }

  render() {
    const { defaultOptions, placeholder } = this.props;
    const { selectedOption } = this.state;
    return (
      <AsyncSelect
        cacheOptions
        value={selectedOption}
        noOptionsMessage={this.noOptionsMessage}
        getOptionValue={this.getOptionValue}
        getOptionLabel={this.getOptionLabel}
        defaultOptions={defaultOptions}
        loadOptions={this.getOptions}
        placeholder={placeholder}
        onChange={this.handleChange}
      />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 您不需要映射结果集的方法。有道具可以为您处理。
  2. 如果您i18n.get()是返回字符串的同步方法,则不必重写整个组件(即使是样式更改)
  3. 如果默认actionOnSelectedOption使用noop方法,则不再需要条件调用它。
  4. inputValue内部选择反应轨道。除非您有外部需求(您的包装器),否则无需尝试管理其状态。
  5. defaultOptions 或者是
    • 一组默认选项(在loadOptions您进行过滤之前不会调用)
    • true(将从您的loadOptions方法自动加载)
  6. 异步/等待函数使用承诺响应而不是callback类型返回承诺。

我想知道通过将getOptions()方法包装在debounce中是否会破坏this组件的作用域。不能肯定地说,因为我从未使用debounce过。您可以拉那个包装器,然后尝试测试代码。


Sha*_*kil 7

我发现人们打算寻找这个问题。因此,我要发布解决问题的代码的更新部分。从异步等待转换为正常的回调函数解决了我的问题。特别感谢Steve和其他人。

import React from 'react';
import AsyncSelect from 'react-select/lib/Async';
import { loadingMessage, noOptionsMessage } from './utils';
import _ from 'lodash';

class SearchableSelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedOption: this.props.defaultValue
    };
    this.getOptions = _.debounce(this.getOptions.bind(this), 500);
  }

  handleChange = selectedOption => {
    this.setState({
      selectedOption: selectedOption
    });
    if (this.props.actionOnSelectedOption) {
      this.props.actionOnSelectedOption(selectedOption.value);
    }
  };

  mapOptionsToValues = options => {
    return options.map(option => ({
      value: option.id,
      label: option.name
    }));
  };

  getOptions = (inputValue, callback) => {
    if (!inputValue) {
      return callback([]);
    }

    const { searchApiUrl } = this.props;
    const limit =
      this.props.limit || process.env['REACT_APP_DROPDOWN_ITEMS_LIMIT'] || 5;
    const queryAdder = searchApiUrl.indexOf('?') === -1 ? '?' : '&';
    const fetchURL = `${searchApiUrl}${queryAdder}search=${inputValue}&limit=${limit}`;

    fetch(fetchURL).then(response => {
      response.json().then(data => {
        const results = data.results;
        if (this.props.mapOptionsToValues)
          callback(this.props.mapOptionsToValues(results));
        else callback(this.mapOptionsToValues(results));
      });
    });
  };

  render() {
    const { defaultOptions, placeholder, inputId } = this.props;
    return (
      <AsyncSelect
        inputId={inputId}
        cacheOptions
        value={this.state.selectedOption}
        defaultOptions={defaultOptions}
        loadOptions={this.getOptions}
        placeholder={placeholder}
        onChange={this.handleChange}
        noOptionsMessage={noOptionsMessage}
        loadingMessage={loadingMessage}
      />
    );
  }
}

export default SearchableSelect;
Run Code Online (Sandbox Code Playgroud)