给定在react-select (https://jedwatson.github.io/react-select/)中进行的选择,我使用axios (https://github.com/mzabriskie/axios)从远程url抓取数据,以便填充页面上的第二个react-select。
诀窍是,我认为我的用例与异步示例的不同之处在于,我不希望用户必须在第二个select中键入内容来触发自动填充。我希望当数据从AJAX调用返回时,自动填充立即发生
我已经确认我正确地获取了远程数据,但是我不能确定react-select的loadOptions参数的正确语法。代码中最接近我想要的示例是来自项目示例的这个函数
https://github.com/JedWatson/react-select/blob/master/examples/src/components/GithubUsers.js#L36
感谢你能提供的任何建议
发布于 2018-10-12 00:33:56
看起来您正在尝试执行相关的select类型的场景,其中传递了第二个select将使用的额外参数,并且您需要open上的新选项。
我通过覆盖AsyncSelect并调整我的loadOptions实现了这一点(使用当前的构建)。
import Select from 'react-select/lib/Async';
export default class AsyncSelect extends Select {
/**
* reload()
* Called when optional load arguments change, to reload the
* data from remote source with new options
* loadOptions={
* (inputValue) => this.props.loadOptions(
* inputValue,
* this.props.loadArguments
* )
* }
*/
reload() {
this.loadOptions('', options => {
const isLoading = !!this.lastRequest;
this.setState({ defaultOptions: options || [], isLoading });
});
}
componentWillReceiveProps(nextProps) {
// if the cacheOptions prop changes, clear the cache, force a reload
if (nextProps.cacheOptions !== this.props.cacheOptions) {
this.optionsCache = {};
}
/**
* loadArguments
* Optional property used in the remote request.
* If these change externally, then the options should be reloaded.
* This is handy for things like related selects.
*/
if (nextProps.loadArguments !== this.props.loadArguments) {
this.reload();
}
if (nextProps.defaultOptions !== this.props.defaultOptions) {
this.setState({
defaultOptions: Array.isArray(nextProps.defaultOptions)
? nextProps.defaultOptions
: undefined
});
}
}
}然后,在我的组件中:
const {loadArguments, myLoadFunc, ...attributes} = this.props;
return (
<AsyncSelect
{...attributes}
className={classes}
defaultOptions
loadArguments={loadArguments}
loadOptions={(inputValue) => myLoadFunc(inputValue, loadArguments)}
value={selected}
onChange={this.onChange}
/>
);发布于 2017-11-18 18:34:09
在github异步示例中,输入参数getUsers(input)是搜索文本。
您可以将第一个react-select值存储在组件状态中,然后loadOptions promise将使用此状态值firstSelectValue获取端点
getUsers() {
return fetch(`https://api.github.com/search/users?q=${this.state.firstSelectValue}`)
.then((response) => response.json())
.then((json) => {
return { options: json.items };
});
}https://stackoverflow.com/questions/45151914
复制相似问题