2017-07-26 66 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!