在React.js中使用componentWillMount等函数的目的是什么?

Adi*_*ran 23 javascript user-interface frontend reactjs react-jsx

我最近在React.js中编写组件.我从来没有使用像componentWillMount和的方法componentDidMount.

render是不可或缺的. getInitialState我写的其他辅助方法也派上用场了.但不是前面提到的两种生命周期方法.

我目前的猜测是它们用于调试?我可以在其中调用console.log:

componentWillMount: function() {
  console.log('component currently mounting');
},

componentDidMount: function() {
  console.log('component has mounted');
} 
Run Code Online (Sandbox Code Playgroud)

还有其他用途吗?

Cym*_*men 25

componentDidMount如果你想使用一些非React JavaScript插件,这是很有用的.例如,React中缺少一个好的日期选择器.Pickaday是美丽的,它只是简单的开箱即用.所以我的DateRangeInput组件现在使用Pickaday作为开始和结束日期输入,我把它连接起来:

  componentDidMount: function() {
    new Pikaday({
      field: React.findDOMNode(this.refs.start),
      format: 'MM/DD/YYYY',
      onSelect: this.onChangeStart
    });

    new Pikaday({
      field: React.findDOMNode(this.refs.end),
      format: 'MM/DD/YYYY',
      onSelect: this.onChangeEnd
    });
  },
Run Code Online (Sandbox Code Playgroud)

需要为Pikaday呈现DOM以连接它,并且componentDidMount钩子允许您挂钩到该确切事件.

componentWillMount在组件安装之前想要以编程方式执行某些操作时非常有用.我正在研究的一个代码库中的一个例子是一个mixin,它有一堆代码,否则它们将被复制到许多不同的菜单组件中.componentWillMount用于设置一个特定共享属性的状态.componentWillMount可以使用的另一种方法是通过prop(s)设置组件分支的行为:

  componentWillMount() {
    let mode;
    if (this.props.age > 70) {
      mode = 'old';
    } else if (this.props.age < 18) {
      mode = 'young';
    } else {
      mode = 'middle';
    }
    this.setState({ mode });
  }
Run Code Online (Sandbox Code Playgroud)


Jon*_*Jon 5

componentDidMount仅在客户端运行一次。这很重要,特别是如果您正在编写同构应用程序(在客户端和服务器上运行)。您可以使用 componentDidMount 来执行需要访问窗口或 DOM 的任务。

来自 Facebook 的 React 页面

If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.
Run Code Online (Sandbox Code Playgroud)

componentWillMount用例较少(我并没有真正使用它),但它的不同之处在于它同时在客户端和服务器端运行。您可能不想将事件侦听器或 DOM 操作放在这里,因为它会无缘无故地尝试在服务器上运行。

  • 由于 React 是 javascript,因此它最酷的事情之一是您可以在节点以及浏览器中运行代码。这意味着您可以为服务器和客户端拥有本质上相同的代码库。一个例子是运行一个 Node Express 服务器,它接受 http 请求,运行 React 和函数 renderToString,然后发送结果字符串作为其响应。https://github.com/mhart/react-server-example (6认同)