Reactjs 反应-使用Superagent等待请求结束

Reactjs 反应-使用Superagent等待请求结束,reactjs,request,state,wait,superagent,Reactjs,Request,State,Wait,Superagent,在ComponentWillMount中,我正在使用Superagent从Node.js获取数据 componentWillMount() { request.get("/appData").end((error, response) => { if (!error && response) { this.setState({ dataJSON: response.body }); } else { con

ComponentWillMount
中,我正在使用Superagent从Node.js获取数据

  componentWillMount() {
    request.get("/appData").end((error, response) => {
      if (!error && response) {
        this.setState({ dataJSON: response.body });
      } else {
        console.log("There was an error fetching server", error);
      }
    });
  }
此数据保存在This.state.dataJSON中,以便在
render()
中呈现

问题是在
setState()
生效之前调用了
render()
。 但是,一旦
setState()
更新了dataJSON的状态,就会再次调用render并呈现数据


因此,我要求您提供一种等待dataJSON更新的解决方案,以便仅在dataJSON更新时调用呈现

在React()中没有延迟渲染这样的事情

你可以做两件事:

  • 在父组件中加载该状态,并仅在拥有数据时装载子组件
  • 使所示组件的
    render()
    检查其是否仍在加载,如果未准备好,则显示加载消息或返回
    null

为什么不在数据尚未提取时简单地显示一种加载图标?延迟渲染将显示一个空白页。这是一个很好的解决方案,但我甚至不知道如何做。假设您在构造函数中将
state.dataJSON
初始化为
null
。然后在渲染中,您可以执行:
if(this.state.dataJSON==null){return Loading}else{return your data}
是的,这就是我刚才做的,我将采用此解决方案!非常感谢。