joh*_*pin 28 javascript reactjs react-hooks
我经常按照“类架构”编写功能组件,其中所有与组件相关的函数都像类中的方法一样写在其中。
例如,我这里有一个counterAsFloat
与Counter
组件相关的函数。如您所见,我只是在组件内部编写了它:
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)
归档时间: |
|
查看次数: |
5711 次 |
最近记录: |