我在 react
中有一个代码,看起来像这样:
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)
,但浏览器引发了这个错误:
未捕获的类型错误:无法读取 null 的属性“样式”
我知道返回 (<div></div>)
的选项,但我不确定这是否是这种情况下的最佳做法。
谢谢!
原文由 Yuval Pruss 发布,翻译遵循 CC BY-SA 4.0 许可协议
我认为只需在您的部分中添加
{ null }
而不是null
以显示空组件。你试过了吗?