这是一个好用的模式!! 听取ReactJS变化的符号?

Jam*_*mes 0 javascript design-patterns reactjs

我已经在我的项目中采用了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>
      );
    }
  };
Run Code Online (Sandbox Code Playgroud)

!!在ReactJS中,这种符号的使用是一种好的模式/实践吗?

更新:感谢您的回复,他们都是有效的.也许,为了进一步澄清我的问题,请注意,这this.props.postDetails是一个包含许多对象和数组的状态.因此问题是,如果我省略了!!并且this.props.postDetails尚未实例化,因此不包含任何数组author[],我得到undefined错误.

T.J*_*der 5

这与一般的JavaScript有关,而不是与React有关.

不,这种使用!!并不是特别有用.这个:

if (!!this.props.postDetails.author) {
Run Code Online (Sandbox Code Playgroud)

与此相同:

if (this.props.postDetails.author) {
Run Code Online (Sandbox Code Playgroud)

它们都不意味着author包含至少有一个条目的数组,这是您的下一行代码所依赖的.要做到这一点,添加.length或者,与您的特定示例,可能[0]相反(如果author有一个条目,但该条目是一个虚假值):

if (this.props.postDetails.author[0]) {
Run Code Online (Sandbox Code Playgroud)

如果author可能是nullundefined,我们需要做两个检查:

if (this.props.postDetails.author && this.props.postDetails.author[0]) {
Run Code Online (Sandbox Code Playgroud)

由于我们将使用结果,因此最好将结果保存为变量或常量:

const firstAuthor = this.props.postDetails.author && this.props.postDetails.author[0];
if (firstAuthor) {
    return firstAuthor.name;
}
Run Code Online (Sandbox Code Playgroud)

抛出错误的当前代码示例:

console.log("Running");
const author = [];
if (!!author) {
  console.log(author[0].name);
} else {
  console.log("No Author");
}
Run Code Online (Sandbox Code Playgroud)

[0]我们知道什么时候检查的例子author不会是null/ falsy:

console.log("Running");
const author = [];
if (author[0]) {
  console.log(author[0].name);
} else {
  console.log("No Author");
}
Run Code Online (Sandbox Code Playgroud)

双重单向的实施例时author可以是null/ falsy:

console.log("Running");
const author = null;
if (author && author[0]) {
  console.log(author[0].name);
} else {
  console.log("No Author");
}
Run Code Online (Sandbox Code Playgroud)

保存和使用结果的示例:

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)
Run Code Online (Sandbox Code Playgroud)