javascript - 从 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 钩子(也试过了),我尝试过滤掉空值,但它不起作用。似乎具有价值的道具在生命周期的后期出现。不能对道具及其单个字符串执行数组函数。
解决方案
首先,您说“它在道具包含我需要的数据之前发送了大约 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
应该是一个字符串数组,或者它应该只是一个字符串。
推荐阅读
- css - 自动取最大高度 CSS 手写笔
- java - 在android中的自定义视图中将自定义样式设置为textviews
- delphi - Delphi Win64 调试器加载符号有限制吗?
- ios - 使用 AVAudioPlayer 无法通过 Swift 4 播放 .m4a
- mesos - 如何修改部署在 Aurora 调度器上的 Heron 集群中 Aurora 任务的 RAM 需求大小?
- python - 如何修复此错误 builtins.TypeError: expected str, bytes or os.PathLike object, not builtin_function_or_method
- actions-on-google - DialogFlow 应用程序的打开麦克风问题
- python - FOREIGN KEY 约束失败
- html - Bootstrap div 左右浮动
- c++ - 使创建的对象再次等于另一个