React中的闭包 [英] Closures in React

查看:40
本文介绍了React中的闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于事件处理程序,可以在react中使用闭包吗?例如,我在导航中有一些功能和很多菜单在导航组件中,我使用类似以下的内容:

Is it ok use closures in react, for event handlers? For example, i have some function and a lot of menu in navigation and in navigation component i use something like this:

handleMenuClick(path) {
  return () => router.goTo(path)
}
... 
<MenuItem
  handleTouchTap={this.handleMenuClick('/home')}
>

还是我应该只喜欢箭头功能?

or i should prefer just arrow function?

<MenuItem
  handleTouchTap={() => router.goTo('/home')}
>

第一个变体确实使代码更清洁,但是我担心大量此类元素的性能

first variant really make code cleaner, but i'm worried about performance with a large number of such elements

推荐答案

均应避免.

虽然它们都可以工作,但是它们都具有相同的弱点,因为它们是动态创建的,因此会导致不必要的渲染,因此会以不同的对象形式出现.

While they'll both work, they both have the same weakness that they'll cause unnecessary renders because the function is being created dynamically, and will thus present as a different object.

您希望以静态方式创建函数,然后传递给它们,而不是使用其中的任何一种方法.对于诸如 MenuItem 之类的东西,它应该只获取路径的字符串,然后使用在内部进行路由的代码.如果需要路由器,则应将其传递给它.

Instead of either of those, you want to create your functions in a static way and then pass them in. For something like your MenuItem, it should just get the string for the path and then have the code to do the routing inside. If it needs the router, you should pass that in instead.

该函数应该是一个预先 bind 版本的函数(通常在构造函数中)并刚刚传入.

The function should then be a pre-bind-ed function (usually in the constructor) and just passed in.

export class MenuItem extends React.Component {
    constructor() {
      this.handleClick = () => this.props.router.go(this.props.path);
    }

    render() {
      return (
        <Button onClick={ this.handleClick }>Go to link</Button>
      );
    }
}

您可以在构造函数中使用箭头函数.这样就不会重新创建每个渲染函数,因此可以避免不必要的渲染.该模式适用于单行简单功能.对于更复杂的函数,您还可以将它们创建为单独的函数,然后在构造函数中对其进行 bind 绑定.

You can use an arrow function in the constructor. That way it isn't recreated every render function, and thus you avoid unnecessary renders. That pattern works well for single-line simple functions. For more complex functions, you can also create them as a separate function, then bind it in the constructor.

export class MenuItem extends React.Component {
  handleClick() {
    this.props.router.go(this.props.path);
  }

  constructor() {
    this.handleClick = this.handleClick.bind(this);
  }

  render() { /* same as above */ }
}

这样做的目的是每次处理程序都是相同的功能.如果它不同(您上面描述的两种方法都不同),那么React会对该对象进行不必要的重新渲染,因为每次它都会是一个不同的函数.

The point of this is that the handler is the same function every time. If it was different (which both methods you describe above would be), then React would do unnecessary re-renders of the object because it would be a different function every time.

这里有两篇文章,其中有更多详细信息:

Here are two articles which go into more details:

这篇关于React中的闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆