最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React useMemo on a function with return value - Stack Overflow

programmeradmin4浏览0评论

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 user14539016user14539016
Add a ment  | 

2 Answers 2

Reset to default 4

Wrap 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]);
发布评论

评论列表(0)

  1. 暂无评论