首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步填充react-select

异步填充react-select
EN

Stack Overflow用户
提问于 2017-07-18 03:10:54
回答 2查看 2.6K关注 0票数 1

给定在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

感谢你能提供的任何建议

EN

回答 2

Stack Overflow用户

发布于 2018-10-12 00:33:56

看起来您正在尝试执行相关的select类型的场景,其中传递了第二个select将使用的额外参数,并且您需要open上的新选项。

我通过覆盖AsyncSelect并调整我的loadOptions实现了这一点(使用当前的构建)。

代码语言:javascript
复制
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
      });
    }
  }
}

然后,在我的组件中:

代码语言:javascript
复制
const {loadArguments, myLoadFunc, ...attributes} = this.props;
return (
  <AsyncSelect
    {...attributes}
    className={classes}
    defaultOptions
    loadArguments={loadArguments}
    loadOptions={(inputValue) => myLoadFunc(inputValue, loadArguments)}
    value={selected}
    onChange={this.onChange}
  />
);
票数 1
EN

Stack Overflow用户

发布于 2017-11-18 18:34:09

在github异步示例中,输入参数getUsers(input)是搜索文本。

您可以将第一个react-select值存储在组件状态中,然后loadOptions promise将使用此状态值firstSelectValue获取端点

代码语言:javascript
复制
getUsers() {
   return fetch(`https://api.github.com/search/users?q=${this.state.firstSelectValue}`)
     .then((response) => response.json())
     .then((json) => {
        return { options: json.items };
    });
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45151914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档