如何解决在useCallback挂钩中反应setState不能正确设置状态变量?
我在React FunctionComponent中具有以下模式的代码:
const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray,someFunction }) => {
const [someStateObjVar,setSomeStateObjVar] = React.useState({});
const [isFound,setIsFound] = React.useState(false);
const handleSomeEvent = React.useCallback((someAttribute: string) => {
if (someAttribute) {
setSomeStateObjVar(someArray.find(
(arrayElement) => ( arrayElement.attribute === someAttribute )
);
setIsFound(someStateVar ?? false);
}
}
return ( isFound && someStateObjVar ) ? <FoundMatchingComponent /> ? <ComponentNotFound />;
在上面的代码中,具有someAttribute的someArray元素始终存在匹配项。 但是问题是MyComponent始终呈现ComponentNotFound,因为isFound总是在最后一行(返回语句)的值为FALSE。
我能够通过以下重构来解决此问题(插入一个中间变量,但总体逻辑保持不变):
const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray,setIsFound] = React.useState(false);
const handleSomeEvent = React.useCallback((someAttribute: string) => {
let foundElement;
if (someAttribute) {
foundElement = someArray.find(
(arrayElement) => ( arrayElement.attribute === someAttribute )
);
}
if (foundElement) {
setSomeStateObjVar(foundElement);
setIsFound(true);
}
}
return ( isFound && someStateObjVar ) ? <FoundMatchingComponent /> ? <ComponentNotFound />;
使用此代码的第二版,isFound在最后一行正确求值为TRUE,而MyComponent正确呈现FoundMatchingComponent。
您能否解释一下为什么第一个版本不起作用而第二个版本不起作用?
我的猜测是第二个版本中的中间变量为React提供了足够的时间在return语句中正确评估isFound变量,但是我不确定这是解释。任何改进我上面代码的建议也将不胜感激。谢谢。
解决方法
在第一个代码段中,我看不到someStateVar
的定义位置。如果是这种情况,则变量为undefined
,因此setIsFound(someStateVar ?? false)
将始终评估为false。因此,isFound
为假,并且return语句将始终返回<ComponentNotFound />
。
您打算拥有setIsFound(someStateObjVar ?? false)
吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。