【问题标题】:Filter out props from null value从 null 值中过滤掉 props
【发布时间】:2019-08-08 19:30:45
【问题描述】:

我有一个通过道具发送数据的提供者。在道具包含我需要的数据(“mailto”mailadress)之前,它会发送大约 4-5 个空值。由于空数据出现在邮件地址之前,因此道具不可用,因为它没有我需要的数据。因此,我需要以某种方式构建我的代码以在我将 mailadress 或 fitler 取出空值时进行更新。 props 是一个字符串值。

目前我已经尝试过:

constructor() {
  this.state = {
    url: "",
    loading: false
  };
}

public componentDidMount(): void {
  let urls = "";
  if (this.props.url != null && undefined)
    if (this.props.url.length > 0) {
      urls = this.props.url;
    }

  this.setState({
    url: this.state.url + urls
  });
  console.log(this.state.url);
}

public render(): React.ReactElement<ImyProps> {
  var iconStyle = {
    fontSize: ``,
    display: "inline-block",
    color: " #ff0033"
  };

  const { loading, url } = this.state;

  return (
    <div>
      {console.log(this.state.url)}

      <Icon
        style={iconStyle}
        iconName="Lightbulb"
        className="ms-IconExample"
      />

      {this.state.loading && this.state.url && (
        <a href={this.props.url}>
          <p>Test. {this.props.url}</p>
        </a>
      )}
    </div>
  );
}

这里我有一个 componedDitMount 钩子(也试过没有那个),我试图过滤掉空值,它不起作用。似乎具有价值的道具在生命周期的后期出现。不能对道具及其单个字符串执行数组函数。

【问题讨论】:

  • if(this.props.url != null &amp;&amp; undefined) 不是您要查找的 if 语句(您实际上并没有检查 this.props.url 是否为 undefined 您正在检查 undefined 是否有 @987654328 @ 值,它没有)。 if(!this.props.url) 应该足以满足您的工作需求。
  • 这是错误的if(this.props.url != null &amp;&amp; undefined) 一个简单的if(this.props.url != null) 就足够了,因为!=null 运算符同时处理nullundefined
  • @Arte2 试试这个if(!this.props.url)
  • componentDidMount 生命周期仅在组件挂载到 DOM 时被调用 一次
  • 查看这篇关于派生状态的文章reactjs.org/blog/2018/06/07/…

标签: javascript reactjs typescript


【解决方案1】:

首先,你说 “它在 props 包含我需要的数据之前发送了大约 4-5 个 null 值”:这意味着你的 Component 第一次没有你需要的 props渲染。
为什么这件事?因为你使用了componentDidMount(),只有第一次挂载Component时才会调用;在您的情况下,由于您所说的,componentDidMount() 将在 this.props.url 等于 null 时运行。

说,正如部分网友在评论中所说,IF的说法也是错误的。

无论如何,你应该这样写:

componentDidUpdate() {
    if (this.props.url) {
        // Here you have this.props.url with some value    
    }
}

请注意,如果您 100% 确定第一个组件被渲染,那么您实际上不需要实现 componentDidMount,它的 props 不包含您需要的数据。

我没有在IF 语句中编写代码,因为我不确定this.props.url 应该是一个字符串数组,还是应该只是一个字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多