问题
I have a function that is called when the user clicks a button on a popup of a reactjs applicatiomn.
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 });
});
}
I have this code here in 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>
)}
However, the popup is not refreshed. The sendAswer function is being called and executed, but I need to refresh the popup and show the message "Message was sent!" after its execution.
How can I make it?
回答1:
this.setState({sentAnswer: true})
This is the state you are updating but your condition is base on !this.state.sent
.
Either change the condition to !this.state.sentAnswer
or this.setState({sent: true})
. I believe this is what it is and was just mistyped.
来源:https://stackoverflow.com/questions/58760906/reactjs-i-am-trying-to-handle-and-event-in-a-popup-but-the-popup-is-not-being