Reactjs - 我正在尝试处理弹出窗口中的事件,但在事件执行后弹出窗口没有按应有的方式呈现
Reactjs - I am trying to handle and event in a popup, but the popup is not being rendered as it should after an event execution
我有一个函数,当用户单击 reactjs 应用程序弹出窗口上的按钮时调用该函数。
sendAnswer = () => {
event.preventDefault();
console.log(this.answer);
const data = { answer: this.answer };
const requestInfo = {
method: 'POST',
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json'
}),
};
fetch('http://www.mocky.io/v2/5d920649310000d48110ccd7', requestInfo)
.then(response => {
if(response.ok) {
console.log('ok')
this.setState({sentAnswer: true})
return response.json()
}
throw new Error("Erro ao enviar a resposta...");
})
.catch(e => {
this.setState({ message: e.message });
});
}
我在 render() 中有这段代码:
{!this.state.sent ? (
<textarea type="text" id="form10" className="md-textarea form-control" rows="3" onChange={e => this.answer = e.target.value} placeholder="Insira a sua resposta aqui" />
) : (
<Alert color="primary" className="text-center"> Message was sent! </Alert>
)}
但是,弹出窗口没有刷新。正在调用和执行 sendAswer 函数,但我需要刷新弹出窗口并在执行后显示消息 "Message was sent!"。
我怎样才能做到?
this.setState({sentAnswer: true})
这是您正在更新的状态,但您的状态基于 !this.state.sent
。
将条件更改为 !this.state.sentAnswer
或 this.setState({sent: true})
。我相信这就是事实,只是打错了。
我有一个函数,当用户单击 reactjs 应用程序弹出窗口上的按钮时调用该函数。
sendAnswer = () => {
event.preventDefault();
console.log(this.answer);
const data = { answer: this.answer };
const requestInfo = {
method: 'POST',
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json'
}),
};
fetch('http://www.mocky.io/v2/5d920649310000d48110ccd7', requestInfo)
.then(response => {
if(response.ok) {
console.log('ok')
this.setState({sentAnswer: true})
return response.json()
}
throw new Error("Erro ao enviar a resposta...");
})
.catch(e => {
this.setState({ message: e.message });
});
}
我在 render() 中有这段代码:
{!this.state.sent ? (
<textarea type="text" id="form10" className="md-textarea form-control" rows="3" onChange={e => this.answer = e.target.value} placeholder="Insira a sua resposta aqui" />
) : (
<Alert color="primary" className="text-center"> Message was sent! </Alert>
)}
但是,弹出窗口没有刷新。正在调用和执行 sendAswer 函数,但我需要刷新弹出窗口并在执行后显示消息 "Message was sent!"。
我怎样才能做到?
this.setState({sentAnswer: true})
这是您正在更新的状态,但您的状态基于 !this.state.sent
。
将条件更改为 !this.state.sentAnswer
或 this.setState({sent: true})
。我相信这就是事实,只是打错了。