gpt4 book ai didi

javascript - 我应该在每个渲染器上调用一个函数还是在 React 类组件中使用箭头函数?

转载 作者:行者123 更新时间:2023-12-04 08:48:07 24 4
gpt4 key购买 nike

我有以下情况

export default class MyComponent extends Component {

myFunc = dynamicKey => {
// do something with the dynamic key
}

render() {

return (
<Foo>
<button onClick={e => this.myFunc(someDynamicKey1)} />
<button onClick={e => this.myFunc(someDynamicKey2)} />
<button onClick={e => this.myFunc(someDynamicKey3)} />
{/* ... */}
</Foo>
)
}
}

这是一个很常见的情况,但它并不好,因为在每次渲染时它都会创建箭头函数。

因此,作为一种变通方法,我创建了一个函数,该函数返回另一个具有该键的函数。

export default class MyComponent extends Component {

myFunc = dynamicKey => e => {
// do something with the dynamic key
}

render() {

return (
<Foo>
<button onClick={this.myFunc(someDynamicKey1)} />
<button onClick={this.myFunc(someDynamicKey2)} />
<button onClick={this.myFunc(someDynamicKey3)} />
{/* ... */}
</Foo>
)
}
}

现在我不是在每个渲染器上创建一个新函数,而是在每个渲染器上调用一个新函数。

现在我不确定该使用哪一个。在每个渲染器上调用一个函数是一种不好的做法吗?我应该使用箭头函数吗?

最佳答案

使用 curried function 时, 你可以使用 its closure当前范围

export default class MyComponent extends Component {
state = {
counter: 42
}
myFunc = dynamicKey => e => {
// closure on the specific this.state.counter value at time of render.
}
}

虽然在每次渲染时返回一个新函数,但它的闭包在最近的范围

export default class MyComponent extends Component {
state = {
counter: 42
}
myFunc = dynamicKey => {
// closure on this.state.counter value
}
}

因此,这取决于用例是什么。问问自己函数是否需要特定值或最近的值。

注意:如果在每次渲染时都重新声明函数,这就变成了“函数和柯里化(Currying)函数之间的区别”的问题,对于 React 来说这无关紧要,因为两个函数体都会被执行。因此,仅通过内存函数(不要调用使用相同参数调用的函数),您可以获得任何明显的差异。

关于javascript - 我应该在每个渲染器上调用一个函数还是在 React 类组件中使用箭头函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59469412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com