React 组件生命周期注意state不能在cwu方法中修改

Component Specs and Lifecycle

Component Specifications

When creating a component class by invokingReact.createClass(),you should provide a specification object that contains arendermethod and can optionally contain other lifecycle methods described here.

Note:

It is also possible to use plain JavaScript classes as component classes. These classes can implement most of the same methods,though there are some differences. For more information about these differences,please read our documentation aboutES6 classes.

render

ReactElement render()

Therender()method is required.

When called,it should examinethis.propsandthis.stateand return a single child element. This child element can be either a virtual representation of a native DOM component (such as<div />orReact.DOM.div()) or another composite component that you've defined yourself.

You can also returnnullorfalseto indicate that you don't want anything rendered. Behind the scenes,React renders a<noscript>tag to work with our current diffing algorithm. When returningfalse,ReactDOM.findDOMNode(this)will returnnull.

render()function should bepure,meaning that it does not modify component state,it returns the same result each time it's invoked,and it does not read from or write to the DOM or otherwise interact with the browser (e.g.,by usingsetTimeout). If you need to interact with the browser,perform your work incomponentDidMount()or the other lifecycle methods instead. Keepingrender()pure makes server rendering more practical and makes components easier to think about.

getinitialState

object getinitialState()

Invoked once before the component is mounted. The return value will be used as the initial value ofthis.state.

getDefaultProps

object getDefaultProps()

Invoked once and cached when the class is created. Values in the mapping will be set onthis.propsif that prop is not specified by the parent component (i.e. using anincheck).

This method is invoked before any instances are created and thus cannot rely onthis.props. In addition,be aware that any complex objects returned bygetDefaultProps()will be shared across instances,not copied.

propTypes

object propTypes

propTypesobject allows you to validate props being passed to your components. For more information aboutpropTypes,seeReusable Components.

mixins

array mixins

mixinsarray allows you to use mixins to share behavior among multiple components. For more information about mixins,249)"> statics

object statics

staticsobject allows you to define static methods that can be called on the component class. For example:

var MyComponent = React.createClass({
  statics: {
    customMethod: function(foo) {
      return foo === 'bar';
    }
  },
  renderfunction() {
  }
});

MyComponent.customMethod('bar');  // true

Methods defined within this block arestatic,meaning that you can run them before any component instances are created,and the methods do not have access to the props or state of your components. If you want to check the value of props in a static method,have the caller pass in the props as an argument to the static method.

displayName

string displayName

displayNamestring is used in debugging messages. JSX sets this value automatically; seeJSX in Depth.

Lifecycle Methods

VarIoUs methods are executed at specific points in a component's lifecycle.

Mounting: componentwillMount

void componentwillMount()

Invoked once,both on the client and server,immediately before the initial rendering occurs. If you callsetStatewithin this method,85)">render()will see the updated state and will be executed only once despite the state change.

Mounting: componentDidMount

void componentDidMount()

ottom:10px; padding-top:0px; padding-bottom:0px; color:rgb(72,only on the client (not on the server),immediately after the initial rendering occurs. At this point in the lifecycle,you can access any refs to your children (e.g.,to access the underlying DOM representation). ThecomponentDidMount()method of child components is invoked before that of parent components.

If you want to integrate with other JavaScript frameworks,set timers usingsetTimeoutorsetInterval,or send AJAX requests,perform those operations in this method.

Updating: componentwillReceiveProps

void componentwillReceiveProps( object nextProps )

Invoked when a component is receiving new props. This method is not called for the initial render.

Use this as an opportunity to react to a prop transition beforerender()is called by updating the state usingthis.setState(). The old props can be accessed viathis.props. Callingthis.setState()within this function will not trigger an additional render.

componentwillReceivePropsfunction(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

Note:

One common mistake is for code executed during this lifecycle method to assume that props have changed. To understand why this is invalid,readA implies B does not imply B implies A

There is no analogous methodcomponentwillReceiveState. An incoming prop transition may cause a state change,but the opposite is not true. If you need to perform operations in response to a state change,usecomponentwillUpdate.

Updating: shouldComponentUpdate

boolean shouldComponentUpdate(
  object nextProps, object nextState
)

Invoked before rendering when new props or state are being received. This method is not called for the initial render or whenforceUpdateis used.

Use this as an opportunity toreturn falsewhen you're certain that the transition to the new props and state will not require a component update.

shouldComponentUpdatefunction(nextProps, nextState) {
  return nextProps.id !== this.props.id;
}

IfshouldComponentUpdatereturns false,thenrender()will be completely skipped until the next state change. In addition,85)">componentwillUpdateandcomponentDidUpdatewill not be called.

By default,85)">shouldComponentUpdatealways returnstrueto prevent subtle bugs whenstateis mutated in place,but if you are careful to always treatstateas immutable and to read only frompropsandstateinrender()then you can overrideshouldComponentUpdatewith an implementation that compares the old props and state to their replacements.

If performance is a bottleneck,especially with dozens or hundreds of components,85)">shouldComponentUpdateto speed up your app.

Updating: componentwillUpdate

void componentwillUpdate( object nextProps,249)"> Invoked immediately before rendering when new props or state are being received. This method is not called for the initial render.

Use this as an opportunity to perform preparation before an update occurs.

Note:

Youcannotusethis.setState()in this method. If you need to update state in response to a prop change,85)">componentwillReceivePropsinstead.

这里注意一下,setState方法不能在这方法调用,这是因为state改变后,这个方法就会再次调用,使程序陷入死循环。

Updating: componentDidUpdate

void componentDidUpdate( object prevProps, object prevstate )

Invoked immediately after the component's updates are flushed to the DOM. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated.

Unmounting: componentwillUnmount#

void componentwillUnmount()

Invoked immediately before a component is unmounted from the DOM.

Perform any necessary cleanup in this method,such as invalidating timers or cleaning up any DOM elements that were created incomponentDidMount.

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...