1

I have the following code (trimmed the form and some other boilerplate):

import React, { Component } from 'react';
import Modal from 'react-modal';

var responseMessages;
export default class ContactForm extends Component {

handleSubmit(event) {
    responseMessages = []

    fetch('http://127.0.0.1:4000/test', {
        method: 'POST',
        mode: 'cors',
        headers: {
            "Access-Control-Allow-Origin":"*",
            'Content-Type': 'application/json'
            },
        body: JSON.stringify(data)
    }).then((response) => response.json())
    .then((responseJson) => {
        for(var i = 0; i < responseJson.errors.length; i++) {
            responseMessages.push(
                <p>{responseJson.errors[i].msg}</p>
            );
        }
    })
    .then(this.openModal());
}

render() {
  return (
    <div>
    <Modal  isOpen={this.state.modalIsOpen}
            onRequestClose={this.closeModal}
            ariaHideApp={false}
            style={customStyles}>
            <div>
                {responseMessages}
            </div>
   </Modal>
   </div>
)}}

Adding {responseMessages} in the Modal displays nothing, but if I change it to {console.log(responseMessages)} it shows in the console that responseMessages is not empty (it has different length, but not empty) What could be the reason for that?

EDIT: openModal function:

openModal() {
    this.setState({modalIsOpen: true});
}

ResponseJson:

{"errors":[{"location":"body","param":"message","msg":"error message","value":"entered value"}]}
4

1 回答 1

0

这是一个javascript问题,与反应无关。当您编写.then(this.openModal())openModal函数时,将立即调用该函数。所以实际的代码应该是

.then(this.openModal.bind(this));

或使用箭头功能

or .then(() => this.openModal());

如果您正在使用一些自动绑定装饰器,或者如果您在构造函数中绑定函数,那么.then(this.openModal);也应该可以工作。

于 2018-03-08T14:17:08.743 回答