React Modal 与 axios 无限循环

React Modal with axios infinite loop

我的打印语句if (this.props.currentNode.getAttribute("label").toLowerCase() === "data") 被无限次调用,不断打印 in modal 并发送 post 请求,直到模式关闭。

当我将 post 调用放入 ComponentDidMount

时,不会发生这种情况

任何人都可以解释为什么会发生这种情况以及我可以做些什么来避免这种情况吗?

class ConfigurationModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectSource: [],
    };
  }

  el = document.createElement("div");

  componentDidMount() {
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }

  jsonIsEmpty = (obj) => {
    return obj === "[object Object]" ? true : false;
  };

  render() {
    // The gray background
    const backdropStyle = {
      position: "fixed",
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
      backgroundColor: "rgba(0,0,0,0.3)",
      padding: 50,
    };
    if (this.props.currentNode.getAttribute("label").toLowerCase() === "data") {
      console.log("in modal")
      http.post("configure_get_sources", {
        headers: {
          "content-type": "application/json",
        },
      })
        .then((res) => {
          this.setState({ selectSource: res.data });
        });

      var tempConfig = this.jsonIsEmpty(
        this.props.currentNode.getAttribute("configuration")
      )
        ? {}
        : JSON.parse(this.props.currentNode.getAttribute("configuration"));
      let renderedSources = this.state.selectSource.map((item, i) => {
        return (
          <option value={item} key={i} selected={item === tempConfig["Source"]}>
            {item}
          </option>
        );
      });
      return ReactDOM.createPortal(
        <div className="backdrop" style={backdropStyle}>
          <Modal.Dialog>
            <Modal.Header>
              <Modal.Title>Configure Node</Modal.Title>
            </Modal.Header>

            <Modal.Body>
              <div className="container">
                <div className="row">
                  <label className="col-md-4">Data Source: </label>
                  <select className="col-md-7" id="dataSelect">
                    {renderedSources}
                  </select>
                </div>
                <div className="row col-md-3"></div>
              </div>
            </Modal.Body>

            <Modal.Footer>
              <Button variant="secondary" onClick={this.props.onClose}>
                Close
              </Button>
              <Button variant="primary" onClick={this.props.saveModal}>
                Save changes
              </Button>
            </Modal.Footer>
          </Modal.Dialog>
        </div>,
        this.el
      );
    }
    
    return "";
  }
}

export default ConfigurationModal;

您正在 render 中修改组件的状态,这会导致无限循环。由于 react 在每次 propsstate 更改后重新渲染组件。 https://reactjs.org/docs/faq-state.html