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