函数式组件:在组件内部还是外部编写函数?

joh*_*pin 28 javascript reactjs react-hooks

我经常按照“类架构”编写功能组件,其中所有与组件相关的函数都像类中的方法一样写在其中。

例如,我这里有一个counterAsFloatCounter组件相关的函数。如您所见,我只是在组件内部编写了它:

export default function Counter() {
  const [counter, setCounter] = React.useState(0);

  const counterAsFloat = () => {
    return counter.toFixed(2);
  };

  return (
    <div className="counter">
      <h1>{counterAsFloat()}</h1>
      <button onClick={() => setCounter(counter + 1)}>
        Increment
      </button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

但实际上我也可以只在组件外部声明函数并使用它的参数:

const counterAsFloat = (counter) => { 
  return counter.toFixed(2);
};

export default function Counter() {
  const [counter, setCounter] = React.useState(0);

  return (
    <div className="counter">
      <h1>{counterAsFloat(counter)}</h1>
      <button onClick={() => setCounter(counter + 1)}>
        Increment
      </button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

那么在功能组件之外编写函数有什么好处或坏处吗?

Den*_*ash 20

This question is pretty opinion-based but there are few notes that you need to think about.

Declaring the function outside of scope is foremost for readability and reusability.

// Reuse logic in other components
const counterAsFloat = (counter) => { 
  return counter.toFixed(2);
};

// If Counter has complex logic, you sometimes want to compose it
// from functions to make it more readable.
export default function Counter() {
  ...

  return (...);
}
Run Code Online (Sandbox Code Playgroud)

One can argue that the first option is less performant because you declare the function on every render:

export default function Counter() {
  ...

  // declare the function on every render
  const counterAsFloat = () => {
    return counter.toFixed(2);
  };

  return (...);
}
Run Code Online (Sandbox Code Playgroud)

这种情况是过早的优化。查看与此相关的JavaScript 闭包性能

请注意,在这种特定情况下,内联函数是更好的方法。

export default function Counter() {
  ...
  return (
    <div>
      <h1>{counter.toFixed(2)}</h1>
      ...
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 我冒昧地修复了一些拼写错误的问题。如果我以您不同意的方式更改了某些内容,请随时使用“恢复编辑”选项。:-) (2认同)
  • @MuhammadUmarFarooq - 哈哈,不相信。:-) 我经常出错。 (2认同)