reactjs - 在 setState 之后,react 中的输入搜索为空
问题描述
如果我在搜索字段中输入一些字母,我想进行 get 查询。但是如果我调用 setState 输入字段总是设置为空。谢谢你的帮助。xxxxxxxxxxxxxxxxxxxxxxxx
constructor() {
super();
this.state = {
isFetching: false,
user: []
};
this.suche = this.suche.bind(this);
}
async suche(e) {
const name = e.target.value;
const ergebnis = await axios
.get("http://HOST:PORT/BACKEND/SERVLET?Param1")
.then(res => {
const user = res.data;
this.setState({ user });
});
}
render() {
return (
<Col md="4">
<label
className="field a-field a-field_a2"
style={{ width: "100%", marginBottom: "10%" }}
>
<input
className="field__input a-field__input"
placeholder="z.B. Hans"
required
onChange={this.suche}
/>
<span className="a-field__label-wrap">
<span className="a-field__label">Name</span>
</span>
</label>
</Col>
);
}
这是我的用户数组
解决方案
user
保存与查询匹配的用户列表,因此您需要一个额外的状态值。让我们调用它query
,然后在输入更改时更新,query
并在成功的 API 调用时更新user
列表。
this.state = {
isFetching: false,
user: [],
query: ""
};
async suche(e) {
const name = e.target.value;
this.setState({ query: name });
const ergebnis = await axios
.get("http://HOST:PORT/BACKEND/SERVLET?Param1")
.then(res => {
const user = res.data;
this.setState({ user });
});
}
并显示在输入字段中输入的值:
<input
className="field__input a-field__input"
placeholder="z.B. Hans"
required
onChange={this.suche}
value={this.state.query}
/>
推荐阅读
- c# - 如何使用 Xamarin.Forms 中的 LibVLCSharp 使我的 RTSP 流存活时间超过 60 秒?
- python - 检查关于年、月、日的错误
- reactjs - 过滤和更改列表 React
- android - 滚动视图不断丢弃底部视图显示
- ios - Swift 4 在索引处添加和删除自定义单元格:0 动画
- sql-server - 如何在 SQL Server 2012 中配置数据库邮件
- r - 用于 Hive 查询的 R 系统命令
- java - JAVA - 使用密钥库对 AWS Elastic Beanstalk 内的 Web 服务进行 SSL 调用
- c++ - 法丽达公主 on Spoj
- jquery - Datatables Jquery - 找不到匹配的记录