gpt4 book ai didi

javascript - React js数组中的警告

转载 作者:行者123 更新时间:2023-11-30 20:02:37 24 4
gpt4 key购买 nike

我有这个功能

static getDerivedStateFromProps(nextProps, prevState) {
let { fetching } = nextProps
const { error } = nextProps

if (prevState.fetching !== fetching && !fetching) {
fetching = error
}
const userId =
Object.keys(nextProps.match.params).length > 0
? nextProps.match.params[Object.keys(nextProps.match.params)[0]]
: 'new'
if (userId !== 'new') {
const itemUser = nextProps.usersList.filter(item => {
if (String(item.userid) === userId)
return item
})
return { profileItem: { ...prevState.profileItem, ...itemUser[0] }, index: userId, fetching }
}
return { fetching }
}

它可以正常工作并按预期执行,但我想摆脱此警告:

Expected to return a value at the end of arrow function array-callback-return

网上说有问题

const itemUser = nextProps.usersList.filter(item => {

最佳答案

filter的回调希望您返回一个 bool 值,您可以将该行重写为:

const itemUser = nextProps.usersList.filter(item => String(item.userid) === userId)

问题存在,因为这个函数:

item => {
if (String(item.userid) === userId)
return item
}

如果 item.userid != userId,您当前未返回任何内容,因此它隐式返回 undefined。这是good practice始终返回某物,即使它为 null 或 false。在这种情况下,您的函数按预期工作,因为 filter callback期望一个 bool 值。当您退回商品时,商品为 truthy因此过滤器包括该项目。此外,如果您不返回任何内容,它会隐式返回 undefined,即 falsy , 从而过滤掉该项目。

最后,由于您要退回一件商品,因此理想情况下应该使用 .find()反而。这将防止在找到项目后进行过多的迭代,因为您只会查找一个项目:

const itemUser = nextProps.usersList.find(item => String(item.userid) === userId);
return { profileItem: { ...prevState.profileItem, ...itemUser }, index: userId, fetching }

关于javascript - React js数组中的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53214190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com