javascript - 这是一个很好用的模式吗?监听 ReactJS 变化的符号?

标签 javascript reactjs design-patterns

我在我的项目中采用 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可能为nullundefined,我们需要做两项检查:

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/

相关文章:

javascript - 为什么我无法从 Node.js 中的扩展 EventEmitter 类捕获事件?

c# - 从父类到其派生类的通信设计模式

java - 以不同方式从另一个对象创建一个对象的设计模式

design-patterns - 最被过度使用的设计示例是什么?如果你有更好的例子,请提供

javascript - 如何加快浏览器的滚动速度?

javascript - 检测所选元素

javascript - 使用 native javascript 查找包含特定 CSS 类的第一个数组元素的索引

javascript - React 中的倒计时器

javascript - 如何在 JSX 的三元运算符中调用两个函数?

javascript - 无法获取图像