粗箭头componentDidMount

时间:2018-10-26 16:04:04

标签: reactjs arrow-functions

我在旧版代码中找到

componentDidMount = () => {
...
}

我知道这是无效的,但可以。现在,我很好奇这和正确方法之间有什么区别

componentDidMount() {
...
}

3 个答案:

答案 0 :(得分:4)

您好,您基本上可以做到这一点,但这不是不必要的原因,也可能损害性能。因为每次函数执行箭头操作,它都必须创建一个新的函数对象。因此,这只是一个优化选择。

好的主题和文章:

答案 1 :(得分:0)

我认为没有什么区别。

但是() => {}返回的内容(隐式),我不认为componentDidMount()返回的内容也不是“更好”

所以我会这样写(如在文档中一样)

componentDidMount() {
...
}

答案 2 :(得分:0)

React中的箭头函数和函数声明的工作方式与它们在原始JS中的工作方式相同。

componentDidMount = () => { //箭头功能

componentDidMount() { //函数声明

与这些函数在React中是特定于类的含义相同。但是,当您看到箭头函数和函数声明在创建并将它们作为处理程序传递给其他组件时的行为时,事情就会变得有趣。

看看这个例子

export default class Parent extends Component {
  constructor() {
    super();
    this.state = {
      time: new Date().toLocaleTimeString()
    };

    // no function binding necessary

  }

  updateTime = () => { // arrow function used here
    this.setState({ // `this` here will be bound to Parent implicitely
      time: new Date().toLocaleTimeString()
    });
  };

  render() {
    return (
      <div>
        <div>Parent: {this.state.time}</div>
        <button onClick={() => this.updateTime()}>Button in Parent</button>
        <Child
          time={new Date().toLocaleTimeString()}
          updateTimeHandler={this.updateTime}
        />
      </div>
    );
  }
}

// updateTimeHandler will be implicitly bound
// to Parent's context
const Child = ({ time, updateTimeHandler }) => {
  return (
    <div>
      <div>Child: {time}</div>
      <button onClick={() => updateTimeHandler()}>Button in Child</button>
    </div>
  );
};

export default Child;

现在,当您不使用箭头时,

export default class Parent extends Component {
  constructor() {
    super();
    this.state = {
      time: new Date().toLocaleTimeString()
    };
    // you have to bind the function to this class
    // if you don't, then `this.` in the method
    // will execute in child's context and throw an error
    this.updateTime = this.updateTime.bind(this);
  }

  updateTime() { // function declaration
    this.setState({
      time: new Date().toLocaleTimeString()
    });
  }

  render() {
    return (
      <div>
        <div>Parent: {this.state.time}</div>
        <button onClick={() => this.updateTime()}>Button in Parent</button>
        <Child
          time={new Date().toLocaleTimeString()}
          updateTimeHandler={this.updateTime}
        />
      </div>
    );
  }
}

// updateTimeHandler will execute in Parent's context
// as we explicitly told so
const Child = ({ time, updateTimeHandler }) => {
  return (
    <div>
      <div>Child: {time}</div>
      <button onClick={() => updateTimeHandler()}>Button in Child</button>
    </div>
  );
};

export default Child;

您可以在此代码沙箱中试用并亲自查看。

https://codesandbox.io/s/j78y87npkv

除此行为外,其他答案中还提到了明显的性能差异。