【问题标题】:How to clear the input after posting the data through fetch and making the code execute successful通过fetch发布数据后如何清除输入并使代码执行成功
【发布时间】:2020-03-21 12:10:48
【问题描述】:

我是 react 新手,使用 reactjs 创建了一个聊天。我正在通过 fetch 使用“POST”请求来发布特定对话的新消息。我的目标是当我发送消息时,它应该清除输入但在发送消息后无法清除输入。还需要写错误。任何人都可以帮助我吗?

我的代码:

handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  handleSend = event => {
    const { phonNo } = this.props.phonNo;
    event.preventDefault();
    console.log("phone : " + "+" + phonNo);
    this.setState({ toPhoneno: phonNo });
    console.log("phonefkjdk : " + "+" + this.state.toPhoneno);
    const data = {
      toPhoneno: "+" + this.state.toPhoneno,
      body: this.state.body
    };
    fetch("/api/messages", {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" }
    })
      .then(res => res.json())
      .then(() => {});
  };
  render () {
    return (
      <div>
        <input
          className="sendMessage"
          onChange={this.handleChange}

        />
        <Button onClick={this.handleSend} className="sendBtn" icon>
          <Icon name="send" color="blue" />
        </Button>
      </div>
    );
  }

任何人都可以帮助我吗?提前致谢

【问题讨论】:

  • 我认为您不需要将toPhoneno 保存到状态中。您的对象解构也不正确,应该是const { phonNo } = this.props;。您的 &lt;input /&gt; 不受控制,因为您没有将 value 道具传递给它。如果是受控组件,您可以setState清除输入。
  • @VahidAkhtar - 我认为它不是重复的
  • @Chandan 您想在发布到后端后让您的输入字段为空吗?
  • @dev_junwen - 我需要在哪里提供 setState?我的意思是在 fetch 下面还是我们需要在 onClick 函数中写入?

标签: reactjs


【解决方案1】:

你可以在 fetch Promise 链的末尾清除它。

fetch("/api/messages", {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" }
    })
      .then(res => res.json())
      .then(() => {
        this.setState({ sendMessage: "" })
      });

输入应该被控制并且应该有一个名字。

  render () {
    return (
      <div>
        <input
          className="sendMessage"
          name="sendMessage"
          value={this.state.sendMessage}
          onChange={this.handleChange}

        />
        <Button onClick={this.handleSend} className="sendBtn" icon>
          <Icon name="send" color="blue" />
        </Button>
      </div>
    );
  }

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    相关资源
    最近更新 更多