如何在通过 fetch 发布数据并使代码成功执行后清除输入



我是新手,使用 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>
);
}

谁能帮我这个?提前致谢

您可以在获取承诺链的末尾清除它。

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>
);
}

最新更新