即使条件变量已正确设置,ReactJS条件渲染也不会显示

时间:2019-04-29 17:23:36

标签: reactjs conditional-rendering

我正在尝试在onClick事件之后渲染微调器,因此在运行另一个函数(在本例中为我的glitcher()函数)时,将显示加载图标。我的渲染功能如下。 onClick调用一个处理程序,该处理程序对状态设置进行排序,如下所示。

现在,onClick调用handleGlitch,并且状态glitchLoading正确设置为true(在条件内用console.log调用进行了测试),但微调器不呈现。

onClick处理程序handleGlitch():

  handleGlitch() {
    this.setState({ glitchLoading: true }, () => {
      this.glitcher()
    }); 
  } 

渲染功能:

render() {
    let previewImage = null;
    let loader = null; 
    if (this.state.originalFiles.length !== 0) {
      previewImage = <img className="folder-icon" src={placeholder} alt="" />;
    }
    if(this.state.glitchLoading) {
      console.log("loading"); 
      loader = <Spinner color="primary" />; 
    }

    return (
      <Container className="previewComponent">
        <Row>
          <Col>
            <legend>
              <b>Upload Images:</b>
            </legend>
            <input
              className="fileInput"
              id="myfileinput"
              type="file"
              onChange={this.handleShow}
              multiple
            />
          </Col>
        </Row>
        <Row>
          <Col className="uploadField">
            <Container className="imgPreview">{previewImage}</Container>
          </Col>
          <Col className="optionField">
            <OptionsForm
              value={this.state.distortion}
              valueChange={value => {
                this.setState({ distortion: value });
              }}
            />
            <Button
              color="danger"
              onClick={this.handleGlitch}
              className="glitch-button"
            >
              Glitch Images
            </Button>
            {loader}
          </Col>
        </Row>
      </Container>
    );
  }

2 个答案:

答案 0 :(得分:0)

也许尝试将其绑定到您的onClick函数。 onClick = {this.handleGlitch.bind(this)}

答案 1 :(得分:0)

我偶然发现了一个解决方案。出于某种原因,将对this.glitcher()的调用以1毫秒的延迟包装在setTimeout中。参见下文:

handleGlitch() {
    this.setState({ glitchLoading: true }, () => {
      setTimeout(() => {
        this.glitcher()
      }, 1); 
    }); 
  }