我正在尝试 ReactJS,但在将其合并到我的表单中时遇到了困难。我正在 ReactJS 中构建一个自动建议表单。在我的onChangeQuery
,我正在设置状态,然后调用 AJAX 函数以从服务器端代码中获取建议;但是,我注意到loadGroupsFromServer
函数未获取最新状态...一键击键速度太慢。我知道setState
不是瞬时的,但那我为什么要使用setState
对于我的表格?使用 ref 更好吗?最好只从中获取价值e.target.value
?
Help!
var GroupForm = React.createClass({
getInitialState: function() {
return {query: "", groups: []}
},
componentDidMount: function () {
this.loadGroupsFromServer();
},
loadGroupsFromServer: function () {
$.ajax({
type: "GET",
url: this.props.url,
data: {q: this.state.query},
dataType: 'json',
success: function (groups) {
this.setState({groups: groups});
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
onChangeQuery: function(e) {
this.setState({query: e.target.value})
this.loadGroupsFromServer();
},
render: function() {
return (
<div>
<form class="form form-horizontal">
<div class="col-lg-12">
<input type="text" className="form-control" value={this.state.query} placeholder="Search for groups" onChange={this.onChangeQuery} />
</div>
</form>
<GroupList groups={this.state.groups} />
</div>
)
}
})
setState
接受回调,这可以让你确保this.loadGroupsFromQuery()
仅在之后调用this.state
已更新。
this.setState({...}, function() {
this.loadGroupsFromQuery();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)