[英]Find function in React.JS
我收到的道具数据看起来像
data: [
{
rowNumber: 1,
specification: null,
validationMessage: [
{
isExists: true,
errors: [
{
errorCode: "PredicateValidator",
errorMessage: "ERR: Length value is not in correct "
},
{
errorCode: "PredicateValidator",
errorMessage: "Height Unit is not in correct "
},
]
}
]
},
{
rowNumber: 2,
specification: null,
validationMessage: [
{
isExists: false,
errors: []
}
]
},
]
在渲染中,我有一个按钮,并且我尝试根据我的errorMessage禁用/启用该按钮。 如果我的eoorMessage包含单词“ ERR:”,我将禁用该按钮,否则将启用它。 注意:我的errorMessage可能为空,也可能没有单词“ Err:”。 如果“ ERR:”一词存在我的任何错误消息,我必须禁用该按钮
我已经尝试过了,但是它说x没有定义。 我该如何克服?
render() {
const hasError = this.props.data ? this.props.data.find((x) => x.validationMessage.erros.find(z => z.errorMessage.indexof("ERR:"))) : ''
return (
<div>
{(this.props.data) ?
<div>
(hasError) ?
<Button variant="contained" className={classes.button} onClick={this.handleSave}>Continue</Button>
:
<Button variant="contained" disabled={true} className={classes.button} onClick={this.handleSave}>Continue</Button>
<Button variant="contained" className={classes.button} onClick={this.handleCancle}> Cancel</Button>
</div>
: ''}
</div>
);
您的代码中存在三个问题。
indexOf()
,如果未找到任何元素及其真实值,它将返回-1
。 您应该使用includes()
x.validationMessage.erros
上使用find()
。 首先在erros
添加缺少的r
。 其次。 您需要使用x.validationMessage[0].errors
因为validationMessage
是一个数组。 data
使用find()
,如果您希望所有禁用的按钮都将返回首次出现,则应使用filter()
否则find()
很好。 您的问题对我来说还不清楚。 我假设要获取其中所有"ERR:"
。
如果要检查其中是否包含err
或不使用.some()
let data = [ { rowNumber: 1, specification: null, validationMessage: [ { isExists: true, errors: [ { errorCode: "PredicateValidator", errorMessage: "ERR: Length value is not in correct " }, { errorCode: "PredicateValidator", errorMessage: "Height Unit is not in correct " }, ] } ] }, { rowNumber: 2, specification: null, validationMessage: [ { isExists: false, errors: [] } ] }, ] let newarr = data.filter(x=>x.validationMessage[0].errors.find(a=>a.errorMessage.includes('ERR:'))) let isError = data.some(x=>x.validationMessage[0].errors.find(a=>a.errorMessage.includes('ERR:'))) console.log(isError) console.log(newarr)
首先,您需要修复validationMessage.erros
和.indexof
等拼写错误。 根据您的数据,``应为validationMessage.errors
,而.indexof
应为.indexOf
。
其次,您需要了解indexOf。 当您的数据errorMessage: "ERR: ...
表达式z.errorMessage.indexOf("ERR:"))
将返回0
,该值在boolean中为false
。
要解决此问题,您需要将其更新为z.errorMessage.indexOf("ERR:") >=0
以便hasError变量为:
const hasError = this.props.data ? this.props.data.find((x) => x.validationMessage.erros.find(z => z.errorMessage.indexof("ERR:") >= 0 )) : ''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.