[英]Using react-select Async with loadOptions and redux-form
我正在使用react-select
库来显示选择框。 我正在使用Select.Async
因为我需要从API中提取选项。 我将Select
与loadOptions
一起loadOptions
,它在初始页面渲染期间起作用。 但是,我也在使用redux-form
,它可以动态change
Field
的值(使用change
)。 但是,当我像这样更改Field的值时,输入的值的确发生了变化(并且我可以验证这一点),但是从来没有再次调用react-select的loadOptions
(即使我认为它应该监听一个价值变化)。 我的问题是,是否有一种方法可以在每次输入值更改时动态调用loadOptions?
谢谢,
编辑:在github上回答这里
也许比这更好的解决方案,但是一种快速的方法是为Select.Async
组件设置一个ref
,并在触发更改操作时(例如,输入的更改-您的情况或一个按钮单击事件-如在下面的代码中),您可以更新其选项。 我在他们的文档示例中使用了类似的示例。
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>
)
}
}
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实现的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.