我在我的项目中采用 ReactJS + Redux 已经有几年了。我经常遇到异步情况,我需要组件等待状态更新以进行渲染。通常简单的逻辑!this.props.isFetching ? <Component /> : "Loading..."
就够了。
但是,在某些情况下,我需要检查嵌入在状态对象中的数组的状态。在这些情况下,我的大多数组件最终看起来像这样:
renderPostAuthor = () => {
if (!!this.props.postDetails.author) {
return this.props.postDetails.author[0].name;
} else {
return (
<div>
<StyledTitle variant="subheading" gutterBottom color="primary">
Loading...
</StyledTitle>
</div>
);
}
};
这是使用!!
吗? ReactJS 中的表示法是一个好的模式/实践吗?
更新:感谢您的回复,它们都是有效的。也许,为了进一步澄清我的问题,请注意 this.props.postDetails
是一个状态本身,包含许多对象和数组。因此问题是,如果我省略 !!
和this.props.postDetails
尚未实例化,因此不包含诸如 author[]
之类的数组,我得到undefined
错误。
最佳答案
与 React 相比,这与 JavaScript 的关系更大。
不,使用 !!
并不是特别有用。这:
if (!!this.props.postDetails.author) {
与此相同:
if (this.props.postDetails.author) {
两者都不是,这意味着 author
包含一个至少包含一个条目的数组,您的下一行代码将依赖该条目。为此,请添加 .length
或者,在您的特定示例中,可能添加 [0]
(如果 author
有一个条目,但是输入是一个虚假值):
if (this.props.postDetails.author[0]) {
如果author
可能为null
或undefined
,我们需要做两项检查:
if (this.props.postDetails.author && this.props.postDetails.author[0]) {
由于我们要使用结果,因此最好将结果保存到变量或常量中:
const firstAuthor = this.props.postDetails.author && this.props.postDetails.author[0];
if (firstAuthor) {
return firstAuthor.name;
}
<小时/>
当前代码抛出错误的示例:
console.log("Running");
const author = [];
if (!!author) {
console.log(author[0].name);
} else {
console.log("No Author");
}
当我们知道 author
不会为 null
/falsy 时检查 [0]
的示例:
console.log("Running");
const author = [];
if (author[0]) {
console.log(author[0].name);
} else {
console.log("No Author");
}
当 author
可能为 null
/falsy 时进行双重检查的示例:
console.log("Running");
const author = null;
if (author && author[0]) {
console.log(author[0].name);
} else {
console.log("No Author");
}
保存和使用结果的示例:
function example(author) {
const firstAuthor = author && author[0];
if (firstAuthor) {
return firstAuthor.name;
} else {
return "Loading...";
}
}
console.log(example(null)); // Loading...
console.log(example([])); // Loading...
console.log(example([{name:"Harlan Ellison"}])); // "Harlan Ellison" (RIP)
关于javascript - 这是一个很好用的模式吗?监听 ReactJS 变化的符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51103097/