简体   繁体   English

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

[英]What is the purpose of having functions like componentWillMount in React.js?

I have been writing components in React.js recently. 我最近在React.js中编写组件。 I have never had to use methods like componentWillMount and componentDidMount . 我从来没有使用过componentWillMountcomponentDidMount类的方法。

render is indispensable. render是不可或缺的。 getInitialState and other helper methods I wrote also come in handy. 我写的getInitialState和其他帮助方法也派上用场了。 But not the two aforementioned lifecycle methods. 但不是前面提到的两种生命周期方法。

My current guess is that they are used for debugging? 我目前的猜测是它们用于调试? I can console.log out inside them: 我可以在其中调用console.log:

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

componentDidMount: function() {
  console.log('component has mounted');
} 

Are there any other uses? 还有其他用途吗?

componentDidMount is useful if you want to use some non-React JavaScript plugins. 如果要使用某些非React JavaScript插件, componentDidMount非常有用。 For example, there is a lack of a good date picker in React. 例如,React中缺少一个好的日期选择器。 Pickaday is beautiful and it just plain works out of the box. Pickaday是美丽的,它只是简单的开箱即用。 So my DateRangeInput component is now using Pickaday for the start and end date input and I hooked it up like so: 所以我的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
    });
  },

The DOM needs to be rendered for Pikaday to hook up to it and the componentDidMount hook lets you hook into that exact event. 需要为Pikaday呈现DOM以连接它,并且componentDidMount钩子允许您挂钩到该确切事件。

componentWillMount is useful when you want to do something programatically right before the component mounts. 如果要在组件安装之前以编程方式执行某些操作, componentWillMount非常有用。 An example in one codebase I'm working on is a mixin that has a bunch of code that would otherwise be duplicated in a number of different menu components. 我正在研究的一个代码库中的一个例子是一个mixin,它有一堆代码,否则它们将被复制到许多不同的菜单组件中。 componentWillMount is used to set the state of one specific shared attribute. componentWillMount用于设置一个特定共享属性的状态。 Another way componentWillMount could be used is to set a behaviour of the component branching by prop(s): 可以使用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 });
  }

componentDidMount only runs once and on the client side. componentDidMount仅在客户端运行一次。 This is important, especially if you're writing an isomorphic app (runs on both the client and server). 这很重要,特别是如果您正在编写同构应用程序(在客户端和服务器上运行)。 You can use componentDidMount to perform tasks require you to have access to window or the DOM. 您可以使用componentDidMount执行要求您有权访问窗口或DOM的任务。

From Facebook's React Page 来自Facebook的React Page

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.

componentWillMount has fewer use cases (I don't really use it), but it differs in that it runs both on the client and server side. componentWillMount具有较少的用例(我实际上并没有使用它),但它的不同之处在于它在客户端和服务器端都运行。 You probably don't want to put event listeners or DOM manipulations here, since it will try to run on the server for no reason. 您可能不希望在此处放置事件侦听器或DOM操作,因为它将尝试无缘无故地在服务器上运行。

This is an example of an isomorphic web application that makes use of componentWillMount : https://github.com/coodoo/react-redux-isomorphic-example 这是使用componentWillMount的同构Web应用程序的示例: https//github.com/coodoo/react-redux-isomorphic-example

However, I'm 99% certain that it runs the code inside componentWillMount for no reason on the server side (I think using componentDidMount to ensure it was only run client side would have made more sense) as the code which ensures that fetch promises are fulfilled before rendering the page is in server.js not inside the individual components. 但是,我99%肯定它在服务器端没有任何理由运行componentWillMount的代码(我认为使用componentDidMount确保它只是运行客户端会更有意义)作为确保获取承诺的代码是在呈现页面之前实现的是在server.js中不在单个组件内部。

There is discussion on per-component async fetching here: https://github.com/facebook/react/issues/1739 As far as I can tell, there is not a good use case for componentWillMount as far as isomorphism is concerned at least. 这里有关于每个组件异步提取的讨论: https//github.com/facebook/react/issues/1739据我所知,就同构性至少而言, componentWillMount没有一个好的用例。

In my project which is a dashboarding tool, I have used componentDidMount(). 在我的项目中,这是一个仪表板工具,我使用了componentDidMount()。

On home page previously saved dashboards appear on the sidebar. 在主页上,以前保存的仪表板显示在侧栏上。 I make an ajax call within componentDidMount() of component rendering Homepage, so as to fetch list of dashboards asynchronously after the page has been rendered. 我在组件呈现主页的componentDidMount()中进行ajax调用,以便在呈现页面后异步获取仪表板列表。

Why React Life Cycle Methods? 为什么反应生命周期方法?

Intend to use third-party (Ex D3.js) library with React Component 打算将第三方(Ex D3.js)库与React Component一起使用


class Example extends React.component{
  constructor(){
    // init state
    // will be called only once
  }  
  componentWillMount(){
    // will be called only once
    // will not be triggered when re-rendering
    // usually will fetch data that is needed in order 
    // to render properly from other API
  }
  shouldComponentUpdate(){
      return false
      // will not re-render itself after componentDidMount(){}
  }
  render(){
    return (
      <div id="chart"></div>
    )
  }
  componentDidMount(){
    d3.select(".chart")
      .selectAll("p")
      // d3.js ........
      // d3.js ........
      // Usually, this will trigger React to re-render itself,
      // but this time will not because we have set 
      // shouldComponentUpdate to false
  }
}

Why React wants to do this? 为什么React想要这样做?

Since rendering DOM is an expensive operation, React uses the layer of virtual DOM to update only DOM / DOMs that is/are different from previous state. 由于渲染DOM是一项昂贵的操作,因此React使用虚拟DOM层来仅更新与先前状态不同的DOM / DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM