使用react-select Async与loadOptions和redux-form

时间:2017-07-28 21:09:58

标签: forms reactjs select redux react-select

我正在使用react-select库来显示一个选择框。我正在使用Select.Async,因为我需要从API中提取选项。我将SelectloadOptions一起使用,它在初始页面渲染过程中起作用。但是,我也使用了redux-form,它可以动态更改Field的值(使用change)。但是,当我像这样更改字段的值时,输入的值确实会改变(我可以验证这一点),但是反应选择的loadOptions永远不会被再次调用(即使我认为它应该是听取价值的变化)。我的问题是,每当输入值发生变化时,有没有办法动态调用loadOptions?

谢谢,

编辑:在github here

上回答

2 个答案:

答案 0 :(得分:-1)

这可能是比这更好的解决方案,但快速的方法是将ref设置为Select.Async组件,并在触发更改操作时(如更改输入 - 您的大小写,或一键式点击事件 - 如下面的代码所示),您可以更新其选项。我在their docs的示例中使用了类似的示例。

class YourClass extends React.Component {

  getOptions = (input, callback) => {
    setTimeout(function () {
      callback(null, {
        options: [
          {value: 'one', label: 'One'},
          {value: 'two', label: 'Two'}
        ]
       });
     }, 500);
   };   

  updateOptions = () => {
    this.selectAsync.state.options.push(
      {value: 'three', label: 'Three'}
    )
  }

  render() {
    let props = this.props;

    return (
      <div>
        <Select.Async
          ref={selectAsync => this.selectAsync = selectAsync}
          loadOptions={this.getOptions}
        />
        <button onClick={this.updateOptions}>
          Load more items
        </button>
      </div>
    )
  }
}

答案 1 :(得分:-1)

this.state = {
            store: '',
            
        };
        
         this.handleStoreSelect = this.handleStoreSelect.bind(this);
         
         
          handleStoreSelect = (item) => {
        this.setState({
            store: item.value
        }
    };
    
    <Select.Async
                              
                              name="storeID"
                              value={this.state.store}
                              loadOptions={getStores}
                              onChange={this.handleStoreSelect}
                            />

const getStores = () => {
    return fetch(
          "api to be hit",
          {
              method: 'get',
              headers: {
                  'Content-Type': 'application/json'
              }
          }
        )
          .then(response => {
              if(response.status >= 400){
                  throw new Error("error");
              }
              return response.json()
          })
          .then(stores => {
              let ret = [];


              for(let store of stores) {
                  ret.push({value: store._id, label: store.name})
              }


              return {options: ret};
          })
          .catch(err => {
              console.log('could not fetch data');
              console.log(err);
              return {options: []}
          })

};

使用这个我们可以获取数据并在loadoptions中传递这个对象。 在课堂外复制此代码。而且我发布了要为loadoptions实现的代码

相关问题