我正在使用react-select库来显示一个选择框。我之所以使用Select.Async,是因为我需要从API中提取选项。我在loadOptions中使用Select,它在初始页面渲染期间工作。但是,我也在使用redux-form,它可以动态地更改Field的值(使用change)。然而,当我像这样改变字段的值时,输入的值确实改变了(我可以验证这一点),但是react-select的loadOptions再也不会被调用了(即使我认为它应该监听值的改变)。我的问题是,有没有一种方法可以在每次输入值改变时动态调用loadOptions?
谢谢,
编辑:在github here上回答
发布于 2017-07-29 06:51:02
这可能是一个比这个更好的解决方案,但一个快速的解决方案是为您的Select.Async组件设置一个ref,当一个更改操作被触发时(如输入的更改-您的案例,或一个按钮单击事件-如下面的代码),您可以更新它的选项。我使用了一个与their文档类似的示例。
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>
)
}
}发布于 2017-07-29 14:00:45
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实现的代码
https://stackoverflow.com/questions/45382456
复制相似问题