首页 > 解决方案 > 在 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>
);
}

这是我的用户数组

在此处输入图像描述

标签: reactjs

解决方案


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}           
/>

推荐阅读