2017-07-26 131 views
0

我有一个react代码看起来是这样的:如何在渲染函数中返回空的jsx元素?

class UserManagement extends React.Component { 
 
    constructor() { 
 
     super(); 
 
     this.state = { 
 
      users: undefined, 
 
     }; 
 
    } 
 

 
    componentWillMount() { 
 
     // load the users state with a Promise 
 
     setTimeout(() => { 
 
      this.setState({users: []}); 
 
     }, 800); 
 
    } 
 

 
    render() { 
 
     if (this.state.users === undefined) { 
 
      // until the users state is updated, I want to return an empty element 
 
      return null; 
 
     } 
 

 
     // real site rendering 
 
     return <div>We have users</div>; 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <UserManagement />, 
 
    document.getElementById("root") 
 
);
<div>Will be blank at first while we don't have users, then show "We have users" after 800ms when we have users</div> 
 
<div id="root"></div> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

我的问题是:如何直到返回用户状态返回一个空元素?我试图返回(null)在一些地方建议,但浏览器提出这个错误:

Uncaught TypeError: Cannot read property 'style' of null

我知道回到(<div></div>)的选项,但我不知道这是在这种情况下,最好的做法。

Thnaks!

+0

@Rajesh抛出与'(null)'相同的错误 –

+0

React文档[说你应该能够返回null](https://facebook.github.io/react/docs/conditional-rendering。 html#prevent-component-from-rendering),所以很奇怪这是行不通的。 –

+2

返回'null'工作得很好。请更新您的问题** **可运行[MCVE]使用堆栈片段(在'[<>]'工具栏按钮)以证明这样做的问题。 Stack Snippets支持React,包括JSX; [这是如何做一个](http://meta.stackoverflow.com/questions/338537/)。 –

回答

2

我觉得只是添加{ null }null,在部分显示空组件。

你有没有尝试过了吗?

-1

好了,所以像Facebook says

Since React's release, people have been using work arounds to "render nothing". Usually this means returning an empty or . Some people even got clever and started returning to avoid extraneous DOM nodes. We finally provided a "blessed" solution that allows developers to write meaningful code. Returning null is an explicit indication to React that you do not want anything rendered. Behind the scenes we make this work with a element, though in the future we hope to not put anything in the document. In the mean time, elements do not affect layout in any way, so you can feel safe using null today!