是否可以将箭头函数与新的React Hook语法一起使用?会有什么不同和/或这会导致问题吗?
文档语法:
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
箭头功能:
const Example = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
简短的回答是:是的,你可以。
箭头函数和函数声明/表达式不等效。但是,如果要替换的函数不使用this
,arguments
并且不使用new
调用,那么您可以自由使用您喜欢的任何样式。
使用function
或const
声明功能组件之间的区别与functional expressions
和functional declaration
之间的区别相同
例如Function declarations
在执行任何代码之前加载,而Function expressions
仅在解释器到达该代码行时加载,即渲染使用function
语法创建的功能组件可以在代码中定义之前完成,而如果使用expression
定义它然后需要在使用前声明
因此,简而言之,function declarations
被悬挂,而function expressions
则没有
在使用上述两种语法创建组件方面,只要您使用卷入帐户,就可以使用它们
一样的。每个函数与箭头函数的差异都是相同的(没有它自己的范围)但是对于反应钩子它是相同的