2017-07-26 12 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'を返すことは問題ありません。スタックスニペット( '[<]]'ツールバーボタン)を使用して** runnable ** [mcve]で質問を更新してください。スタックスニペットはJSXを含むReactをサポートします。 [これを行う方法はこちら](http://meta.stackoverflow.com/questions/338537/)。 –

答えて

2

私はちょうど空のコンポーネントを表示するために、あなたのセクションでは、{ null }ないnullを追加すると思います。

すでに試しましたか?

-1

[OK]を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!

関連する問題