私はこのようになります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!
@Rajeshは '(null) 'と同じエラーを投げます –
Reactドキュメント[' null'を返すことができるはずです。](https://facebook.github.io/react/docs/conditional-rendering。 html#prevent-component-from-rendering)、これは動作していないのが奇妙です。 –
'null'を返すことは問題ありません。スタックスニペット( '[<]]'ツールバーボタン)を使用して** runnable ** [mcve]で質問を更新してください。スタックスニペットはJSXを含むReactをサポートします。 [これを行う方法はこちら](http://meta.stackoverflow.com/questions/338537/)。 –