[英]How to add dynamic value from useMemo function into tests with React Testing library?
[英]React useMemo on a function with return value
我有一个简单的 function,它具有基于 if 语句的返回值。 我需要在这个 function 上使用 Memo,它在渲染之间保持相同的值。 我怎样才能做到这一点?
const getStatusState = () => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
};
useMemo 如何在这个 function 上工作,因为我没有使用 useState 我从道具中获取值 a。
用React.useMemo
包装它并将React.useMemo
传递a
依赖数组,这样它只在a
更改时触发。
const getStatusState = React.useMemo(() => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
}, [a]);
仅当您想将getStatusState
用作常量时,上述答案才有效。 如果您将getStatusState
用作 function,它将给出Uncaught TypeError:
。 即:如果您使用控制台在下方登录
const getStatusState = React.useMemo(() => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
}, [a]);
日志将是:
console.log(getStatusState); => 'STRING_A' or 'STRING_B' or 'N/A'
console.log(getStatusState()); => Uncaught TypeError: getStatusState is not a function
要解决上面的问题,使用getStatusState
as function ie: getStatusState()
,在React中有两种方式:
1 使用 useMemo() 并返回一个 Function
const getStatusState = React.useMemo(
() => () => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
},
[a]
);
2 使用 useCallback()
const getStatusState = React.useCallback(() => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
}, [a]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.