首页 > 解决方案 > 从 null 值中过滤掉 props

问题描述

我有一个通过道具发送数据的提供者。在道具包含我需要的数据(“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 钩子(也试过了),我尝试过滤掉空值,但它不起作用。似乎具有价值的道具在生命周期的后期出现。不能对道具及其单个字符串执行数组函数。

标签: javascriptreactjstypescript

解决方案


首先,您说“它在道具包含我需要的数据之前发送了大约 4-5 个空值”:这意味着您的组件在第一次渲染时将没有您需要的道具。
为什么这件事?因为你使用componentDidMount()了,只有在组件第一次挂载时才会调用;在您的情况下,由于您所说的,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应该是一个字符串数组,或者它应该只是一个字符串。


推荐阅读