简体   繁体   English

有没有一种更清洁的方法可以在初始加载时停止React渲染?

[英]Is there a cleaner way to stop React rendering on initial load?

So my react class calls to a json response and then renders. 因此,我的react类会调用json响应,然后进行渲染。

But as it stands, the class will render on initial load then render again when response has come back. 但是按现状,该类将在初始加载时呈现,然后在响应返回时再次呈现。

To get around this I have do this - 为了解决这个问题,我必须这样做-

componentDidMount: function() {

        axios.get.......
          .then(res => {
            const jobs = res.data;
            this.setState({ jobs });
          });
  },

render: function () {
      if (Object.keys(this.state.jobs).length == 0)
      {

      }
      else {
          return (
              <div>
                  {this.state.jobs.data.map(function (ob) {
                      return <li key={ob.id}>{ob.name}</li>

                  })}

              </div>
          )
      }
      return null;
  }

});

Is there a nicer way to do this? 有没有更好的方法可以做到这一点? without using an if statement? 不使用if语句?

React always has to render in the initial load. React总是必须在初始加载中进行渲染。 So you just need to render null like you already did. 因此,您只需要像以前一样渲染null。 Code wise, maybe you can write 明智的代码,也许你可以写

return this.state.jobs.data ? <YourTemplate /> : null;

which is cleaner. 比较干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM