反应在componentdidmount之前调用的渲染

时间:2019-08-21 12:49:57

标签: javascript reactjs react-component

在我的componentDidMount()中,我正在进行API调用“ invokeservice”以获取一些数据,然后此调用设置了我在渲染器中使用的状态对象。

我遇到的问题是没有调用invokeservice并设置了第一次加载页面的时间,但是,当我刷新页面时,invokeservice会很好地返回数据,其余的脚本将运行。这只是它第一次返回空值。

是否可以在渲染函数中调用此调用服务,并在用户尝试加载此页面时保持数据就绪并显示它。

尝试: 1.读取ComponentDidMount仅在第一个初始渲染之后被调用。 2. {this.invokeservice()}我试图在返回之前调用render函数,该函数执行了初始渲染,但是5秒钟后为空白,然后5秒钟后再次用值填充。

渲染功能

public render() {
    return (
        <div className="monitor">
          <div className="monitor__table">                   
            {this.monitorrow(translate("cpu"), this.state.cpuString)}
            {this.monitorrow(translate("memory"), this.state.pmemoryString)}
          </div>
        </div>
    );
  }

构造函数

constructor(props) {
    super(props);
    this.state = {
      cpu: 0,
      cpuString: ""
    };
    setInterval(() => this.invokeservice(), 5000);
  }

componentdidMount

  public componentDidMount() {
    this.invokeservice();
  }

invokeservice

private invokeservice() {

    var client = new HttpClient();

    var url = this.props.baseUrl + '//getMonitorUsage' + '?NC=' + Date.now().toString();

    client.get(url, (response) => {
        this.setState({
          cpu: JSONResponse.GetSystemStateResult.CPUusage

        });
      }
    }
    });
  }

功能

monitorrow(left,right) {
    return (
      <div className="table__row">
        <div className="table__cell__left">
          <Text>{left}</Text>
        </div>
        { right &&
          (<div className="table__cell__right">
            <Text>{right}</Text>
          </div>)
        }
      </div>  
    );
  }

1 个答案:

答案 0 :(得分:2)

这是预期的。

从react docs:

  

在创建组件实例并将其插入DOM时,将按以下顺序调用这些方法:

  • constructor()
  • 静态getDerivedStateFromProps()
  • render()
  • componentDidMount()

参考:https://reactjs.org/docs/react-component.html


componentWillMount,它将在render()之前被调用。但是不建议使用。详细了解官方文档https://reactjs.org/docs/react-component.html#unsafe_componentwillmount