JSX 道具不应该使用 .bind() - 如何避免使用绑定?

2022-01-21 00:00:00 reactjs javascript components

我有一个容器,我需要更改显示表单或显示成功页面的 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()

JSX props should not use .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.

你有两个选择:

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

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

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

  • 或使用 箭头函数创建您的处理程序 所以他们将使用this 的词法上下文,因此你不需要在 bind 他们所有(你需要一个 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.

    相关文章