【问题标题】:Using react-select Async with loadOptions and redux-form使用带有 loadOptions 和 redux-form 的 react-select Async
【发布时间】:2018-01-05 01:15:33
【问题描述】:
我正在使用react-select 库来显示一个选择框。我正在使用Select.Async,因为我需要从 API 中提取我的选项。我使用Select 和loadOptions,它在初始页面渲染期间工作。但是,我也在使用redux-form,它可以动态更改Field 的值(使用change)。但是,当我像这样更改 Field 的值时,输入的值确实会发生变化(我可以验证这一点),但是 react-select 的 loadOptions 再也不会被调用(即使我认为它应该在监听值的变化)。我的问题是,有没有办法在每次输入值更改时动态调用 loadOptions ?
谢谢,
编辑:在 github 上回答 here
【问题讨论】:
标签:
forms
reactjs
select
redux
react-select
【解决方案1】:
这可能是比这更好的解决方案,但一个快速的解决方案是为您的Select.Async 组件设置一个ref,并在触发更改操作时(例如更改输入 - 您的情况,或按钮单击事件 - 如下面的代码所示)您可以更新其选项。我正在使用与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>
)
}
}
【解决方案2】:
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 实现的代码