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)
谢谢您的回答,史蒂夫。仍然没有运气。我会尝试根据您的回应来回应。
异步选择可以完美地用于2/3查询,然后突然停止工作。我观察到一种明显的行为,即在这些情况下搜索指示符(...)也未显示。
非常感谢您抽出宝贵的时间。
再次非常感谢您的回复。我对getOptionValue和getOptionLabel错误。如果loadOptions得到响应,则将调用这两个函数。所以我从以前的代码片段中删除了我的helper optionsValue函数,并根据(也在本帖子中)更新了我的代码片段。但是仍然没有运气。在某些情况下,异步选择无效。我尝试对这种情况进行截图。我在我的本地数据库名称“ tamim johnson”中确实使用了名称,但是当我搜索他时,我没有得到任何回应,但从后端得到了正确的回应。这是此案例的屏幕截图

我不确定此屏幕截图的清晰度如何。塔米姆·约翰逊(Tamim Johnson)在我的排名中也排名第六。
先生,谢谢您的时间。我不知道我在做什么错或错过了什么。
这是名为“ tamim johnson”的用户搜索的预览选项卡响应。
问题是 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
一些注释可以在代码下面找到。您正在寻找这样的东西:
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)
i18n.get()是返回字符串的同步方法,则不必重写整个组件(即使是样式更改)actionOnSelectedOption使用noop方法,则不再需要条件调用它。inputValue内部选择反应轨道。除非您有外部需求(您的包装器),否则无需尝试管理其状态。defaultOptions 或者是
loadOptions您进行过滤之前不会调用)true(将从您的loadOptions方法自动加载)callback类型返回承诺。我想知道通过将getOptions()方法包装在debounce中是否会破坏this组件的作用域。不能肯定地说,因为我从未使用debounce过。您可以拉那个包装器,然后尝试测试代码。
我发现人们打算寻找这个问题。因此,我要发布解决问题的代码的更新部分。从异步等待转换为正常的回调函数解决了我的问题。特别感谢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)
| 归档时间: |
|
| 查看次数: |
8211 次 |
| 最近记录: |