我不知道为什么react-select 会清除我在第二个或第三个字符之后输入的内容。根据我的日志,状态已正确更新。我认为这可能是操作异步发生的,但即使在更新后是这种情况,我也希望选择上的文本根据状态进行更新。除此之外,当从列表中选择一个选项并按 Enter 时,它不会在文本框中显示选择,但它会在更新状态时识别选择。
任何指出我的错误在哪里的方向都将不胜感激。
我的 repo 是分支上的以下内容(virtualizedSelectAsync)
https://github.com/itReverie/itr-react-redux-normalizr/tree/virtualizedSelectAsync
我的组件如下:
class Selector extends Component {
componentWillMount()
{
this.onChange = this.onChange.bind(this);
this.onInputChange = this.onInputChange.bind(this);
this.dispatchSuggestions = this.dispatchSuggestions.bind(this);
}
//I update the state just when an option has been selected
onChange(selectedOption){
let newValue='';
if(selectedOption !== null){
newValue=selectedOption.name;
}
this.props.actions.updateTextSuccess(newValue.toLowerCase(),
this.props.questionId,
this.props.partId)
}
dispatchSuggestions(newTextValue)
{
//First I update the state of the text with the values I want to send to the API and provide me suggestions based on that value
return
this.props.actions.updateTextSuccess(newTextValue.toLowerCase(),
this.props.questionId,
this.props.partId)
.then(data => {
//After updating the text then dispatch the action to load
//the suggestions
return this.props.actions.loadSuggestions(
this.props.parts.get('byPartId'),
this.props.questionId,
this.props.partId)
.then(textUpdated=>{return textUpdated;})})
}
onInputChange (newTextValue)
{ //I just want to dispatch the suggestions after the user has typed
// 3 characters so the API has some context and return the
// necessary suggestions
if(newTextValue.length===3 && newTextValue.trim() !=="")
{
return Promise.resolve( this.dispatchSuggestions(newTextValue))
}
return newTextValue;
}
render () {
let suggestions=[];
if(this.props.part.get('suggestions').size === undefined){
suggestions=this.props.part.get('suggestions');
}
else {
suggestions=this.props.part.get('suggestions').toJS();
}
return (
<VirtualizedSelect style={{width:'180px'}}
options={suggestions}
labelKey='name'
valueKey='name'
value={this.props.part.toJS().text}
onChange={this.onChange}
onInputChange={this.onInputChange}
/>
)
}
}
注意:我使用的是虚拟化选择,但行为与选择相同。