本文介绍了在React.js中拥有诸如componentWillMount之类的功能的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在用React.js编写组件.我从来没有使用过像componentWillMountcomponentDidMount这样的方法.

I have been writing components in React.js recently. I have never had to use methods like componentWillMount and componentDidMount.

render是必不可少的.我编写的getInitialState和其他辅助方法也派上用场.但不是上述两种生命周期方法.

render is indispensable. getInitialState and other helper methods I wrote also come in handy. But not the two aforementioned lifecycle methods.

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

My current guess is that they are used for debugging? I can console.log out inside them:

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

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

还有其他用途吗?

推荐答案

componentDidMount很有用.例如,React中缺少好的日期选择器. Pickaday 很漂亮,开箱即用.因此,我的DateRangeInput组件现在使用Pickaday作为开始日期和结束日期输入,我将其连接起来是这样的:

componentDidMount is useful if you want to use some non-React JavaScript plugins. For example, there is a lack of a good date picker in React. Pickaday is beautiful and it just plain works out of the box. So my DateRangeInput component is now using Pickaday for the start and end date input and I hooked it up like so:

  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
    });
  },

需要为Pikaday渲染DOM才能连接到它,而componentDidMount钩子则可以让您钩住该确切事件.

The DOM needs to be rendered for Pikaday to hook up to it and the componentDidMount hook lets you hook into that exact event.

componentWillMount在您要在组件挂载前以编程方式执行某些操作时很有用.我正在处理的一个代码库中的一个示例是mixin,其中具有一堆代码,否则这些代码将在许多不同的菜单组件中重复. componentWillMount用于设置一个特定共享属性的状态.可以使用componentWillMount的另一种方法是通过prop(s)设置组件分支的行为:

componentWillMount is useful when you want to do something programatically right before the component mounts. 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. componentWillMount is used to set the state of one specific shared attribute. Another way componentWillMount could be used is to set a behaviour of the component branching by 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 });
  }

这篇关于在React.js中拥有诸如componentWillMount之类的功能的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 09:19