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