我可以为 React Hooks 使用箭头函数而不是普通函数吗?
Can I use arrow functions instead of normal functions for React Hooks?
是否可以将箭头函数与新的 React Hook 语法一起使用?有什么不同 and/or 这会导致问题吗?
文档语法:
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>
);
}
一样。区别将与任何函数与箭头函数之间的区别相同(没有它自己的作用域)但是对于反应钩子它是相同的
使用 function
或 const
声明功能组件的区别与 functional expressions
和 functional declaration
之间的区别相同
例如 Function declarations
在执行任何代码之前加载,而 Function expressions
仅在解释器到达该行代码时加载,即渲染使用 function
语法创建的功能组件可以完成在代码中定义之前,如果使用 expression
定义,则需要在使用
之前声明
所以简而言之 function declarations
被提升而 function expressions
没有被提升
在使用上述两种语法创建组件方面你可以使用任何一种只要你使用提升考虑
简短的回答是:可以。
箭头函数和函数declarations/expressions不等价。但是,如果您要替换的函数不使用 this
、arguments
并且未使用 new
调用,那么您可以随意使用您喜欢的任何样式。
TL;DR: 是
但我肯定会向 arrow function
使用 function expression
,因为将它们都用于编写组件会导致防止提升问题。
const MyComponent = ({ someProp }) => (
<div>
{someProp}
</div>
);
使用状态:
const MyComponent = ({ someProp }) => {
const [showText, setShowText] = useState(false);
return (
<div onClick={setShowText}>
{showText && <span>some text</span>}
{someProp}
</div>
);
};
是否可以将箭头函数与新的 React Hook 语法一起使用?有什么不同 and/or 这会导致问题吗?
文档语法:
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>
);
}
一样。区别将与任何函数与箭头函数之间的区别相同(没有它自己的作用域)但是对于反应钩子它是相同的
使用 function
或 const
声明功能组件的区别与 functional expressions
和 functional declaration
例如 Function declarations
在执行任何代码之前加载,而 Function expressions
仅在解释器到达该行代码时加载,即渲染使用 function
语法创建的功能组件可以完成在代码中定义之前,如果使用 expression
定义,则需要在使用
所以简而言之 function declarations
被提升而 function expressions
没有被提升
在使用上述两种语法创建组件方面你可以使用任何一种只要你使用提升考虑
简短的回答是:可以。
箭头函数和函数declarations/expressions不等价。但是,如果您要替换的函数不使用 this
、arguments
并且未使用 new
调用,那么您可以随意使用您喜欢的任何样式。
TL;DR: 是
但我肯定会向 arrow function
使用 function expression
,因为将它们都用于编写组件会导致防止提升问题。
const MyComponent = ({ someProp }) => (
<div>
{someProp}
</div>
);
使用状态:
const MyComponent = ({ someProp }) => {
const [showText, setShowText] = useState(false);
return (
<div onClick={setShowText}>
{showText && <span>some text</span>}
{someProp}
</div>
);
};