[英]How to fix expected to return a value at the end of arrow function warning in react js?
I map an object with objects inside of it like this:我 map 和 object 里面有这样的对象:
{props && Object.keys(props).map((each) => {
if (each !== 'logo' && each !== 'info' && each !== 'mobin') {
return (
<Slide key={each} style={{ height: '200px' }}>
<div
style={{
height: '100%'
}}
onClick={() => handleClick(each)}
className="d-flex justify-content-center align-items-center"
>
<Img
alt="company-logo"
style={{
width: '140px',
cursor: 'pointer'
}}
fluid={props[each].childImageSharp.fluid}
/>
</div>
</Slide>
);
}
})}
It works perfectly but there is a warning in terminal which is:它工作得很好,但终端中有一个警告:
warning Expected to return a value at the end of arrow function array-callback-return
How can I fix the expected to return a value at the end of arrow function?如何修复箭头 function 末尾的预期返回值?
The map
function, as the warning says, is always expected to return a value, at every iteration.正如警告所说,
map
function 总是期望在每次迭代时返回一个值。 Your function returns something only when the condition inside the if statement is true.只有当 if 语句中的条件为真时,您的 function 才会返回某些内容。 In all other cases, nothing is returned.
在所有其他情况下,不返回任何内容。
To fix that, you can just add an else statement:要解决这个问题,您只需添加一个 else 语句:
if (each !== 'logo' && each !== 'info' && each !== 'mobin') {
...
} else {
return null;
}
Another option is to remove if
from within the map
function and use the filter
function like this:另一种选择是从
map
function 中删除if
并使用filter
function ,如下所示:
{props && Object.keys(props)
.filter(each => each !== 'logo' && each !== 'info' && each !== 'mobin')
.map(each => {
return(
......
)})
}
You can also get rid of the explicit if statement:您还可以摆脱显式 if 语句:
{
props &&
Object.keys(props).map((each) => {
return (
each !== 'logo' &&
each !== 'info' &&
each !== 'mobin' && (
<Slide key={each} style={{ height: '200px' }}>
<div
style={{
height: '100%'
}}
onClick={() => handleClick(each)}
className="d-flex justify-content-center align-items-center"
>
<Img
alt="company-logo"
style={{
width: '140px',
cursor: 'pointer'
}}
fluid={props[each].childImageSharp.fluid}
/>
</div>
</Slide>
)
);
});
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.