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

烂漫一生 提交于 2019-12-13 03:39:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!