[英]React. Props error when try to use forEach function
When I try to send the props from parent component Row
by condition via forEach
iterator I even get the undefined
in the child component. 当我尝试通过
forEach
迭代器按条件从父组件Row
发送道具时,我什至在子组件中得到了undefined
。
I cannot figure out what is the problem is... 我不知道问题是什么...
// Parent component
// ... class Row extends...
// ... some code
render() {
const canSelector = {
selectedItems: []
}
return (
<Row showImage={canSelector.selectedItems.forEach(item => {
item.ID === i ? 'item' : 'error'}) }
/>
}
)
// Child component for test
// ... class XXX extends...
// ... some code
const { showImage } = this.props
console.log(showImage); // gets "undefined", intead of "error" string
Array.prototype.forEach() doesn't return anything, that is the reason that you are getting undefined
as the value of showImage
in your <Row />
component. Array.prototype.forEach()不返回任何内容,这就是在
<Row />
组件showImage
undefined
为showImage
值的showImage
。
I assume that you are trying to check if the item.ID
has the same value as i
, and return 'item'
or 'error'
accordingly? 我假设您正在尝试检查
item.ID
是否具有与i
相同的值,并相应地返回'item'
或'error'
?
You might want to check Array.prototype.findIndex() instead. 您可能要检查Array.prototype.findIndex() 。
You can do something like this: 您可以执行以下操作:
<Row showImage={canSelector.selectedItems.findIndex(item => item.ID === i) > -1 ? 'item' : 'error'} />
findIndex()
will return the index of the first item in the array that satisfy the condition provided, else it will return -1
. findIndex()
将返回满足所提供条件的数组中第一项的索引,否则将返回-1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.