How to avoid bind or inline arrow functions inside render method

前端 未结 4 1392
暖寄归人
暖寄归人 2020-11-22 06:10

We should avoid method binding inside render because during re-rendering it will create the new methods instead of using the old one, that will affect the performance.

4条回答
  •  隐瞒了意图╮
    2020-11-22 06:44

    Documentation encourages to use data-attributes and access them from within evt.target.dataset:

    _deleteTodo = (evt) => {
      const elementToDelete = evt.target.dataset.el;
      this.setState(prevState => ({
        todos: prevState.todos.filter(el => el !== elementToDelete)
      }))
    }
    
    // and from render:
    
    todos.map(
      el => 
    {el}
    )

    Also note that this makes sense only when you have performance issues:

    Is it OK to use arrow functions in render methods?

    Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions.

    If you do have performance issues, by all means, optimize!

提交回复
热议问题