JSX道具不应该使用.bind()-如何避免使用bind? [英] JSX props should not use .bind() - how to avoid using bind?

查看:753
本文介绍了JSX道具不应该使用.bind()-如何避免使用bind?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个容器,需要更改显示表单或显示成功页面的UI表单。

I have a container that I need to change the UI form showing the form or showing a success page.

容器具有state.showSuccess,我需要可以调用MyFormModule来更改容器的状态。

The container has a state.showSuccess and I need the MyFormModule to be able to call the container to change the state.

下面的代码有效,但是我收到以下警告:

The below code works but I'm getting the following warning:

JSX道具不应该使用.bind()

如何在不使用.bind的情况下使其工作()?

How can I get this to work without using .bind()?

...
const myPage = class extends React.Component {
  state = { showSuccess: false };
  showSuccess() {
   this.setState({
      showSuccess: true,
    });
  }
  render() {
    const { showSuccess } = this.state;
    if (showSuccess) {...}
    ....
    <MyFormModule showSuccess={this.showSuccess.bind(this)} />


推荐答案

您应首先了解为什么,这是不好的做法

You should first understand WHY this is a bad practice.

此处的主要原因是 .bind 返回新的函数引用。

每次 render 调用都会发生这种情况,这可能会导致性能下降。

The main reason here, is that .bind is returning a new function reference.
This will happen on each render call, which may lead to a performance hit.

您有2个选择:


  1. 使用构造函数来绑定您的处理程序(这只会运行一次)。

  1. Use the constructor to bind your handlers (this will run only once).

constructor(props) {
  super(props);
  this.showSuccess = this.showSuccess.bind(this);
}


  • 或使用箭头函数,以便它们将
    词法上下文用于,因此您无需将它们全部绑定到
    绑定您将需要babel插件):

  • Or create your handlers with arrow functions so they will use the lexical context for this, hence you won't need to bind them at all (you will need a babel plugin):

    showSuccess = () => {
      this.setState({
        showSuccess: true,
      });
    }
    


  • 您应使用此模式(如其他建议):

    You should not use this pattern (as others suggested):

    showSuccess={() => this.showSuccess()}
    

    因为这也会在每个渲染器上创建一个新函数。

    因此,您可以绕过该警告,但仍在以不良做法设计编写代码。

    Because this will as well create a new function on each render.
    So you may bypass the warning but you are still writing your code in a bad practice design.

    ESLint文档


    JSX prop中的绑定调用或箭头函数将创建一个全新的
    在每个渲染上起作用。这对性能不利,因为
    会导致调用垃圾回收器的方式超出了必需的
    的程度。如果将全新的
    函数作为道具传递给使用对道具进行引用
    相等性检查以确定是否应更新的组件,则这也可能导致不必要的重新渲染。

    A bind call or arrow function in a JSX prop will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary. It may also cause unnecessary re-renders if a brand new function is passed as a prop to a component that uses reference equality check on the prop to determine if it should update.

    这篇关于JSX道具不应该使用.bind()-如何避免使用bind?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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