admin管理员组文章数量:1394520
I have a simple function that has return values based on if statements. I need to useMemo on this function that keep the same values between renders. How can I do this?
const getStatusState = () => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
};
How does useMemo work on this function as I am not using useState I am getting the value a from props.
I have a simple function that has return values based on if statements. I need to useMemo on this function that keep the same values between renders. How can I do this?
const getStatusState = () => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
};
How does useMemo work on this function as I am not using useState I am getting the value a from props.
Share Improve this question asked Nov 3, 2020 at 1:58 user14539016user145390162 Answers
Reset to default 4Wrap it with React.useMemo
and pass a
into the dependency array so it fires only if a
changes.
const getStatusState = React.useMemo(() => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
}, [a]);
The above answer is valid only if you want to use getStatusState
as a constant. If you use getStatusState
as a function it will give Uncaught TypeError:
. ie: if you log below using the console
const getStatusState = React.useMemo(() => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
}, [a]);
Logs will be:
console.log(getStatusState); => 'STRING_A' or 'STRING_B' or 'N/A'
console.log(getStatusState()); => Uncaught TypeError: getStatusState is not a function
To solve the above problem and use getStatusState
as function ie: getStatusState()
, there are two ways in React:
1 Using useMemo() and return a Function
const getStatusState = React.useMemo(
() => () => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
},
[a]
);
2 Using useCallback()
const getStatusState = React.useCallback(() => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
}, [a]);
本文标签: javascriptReact useMemo on a function with return valueStack Overflow
版权声明:本文标题:javascript - React useMemo on a function with return value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744100734a2590858.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论