React生命周期理解

render:纯粹的返回值,方便看组件的作用

返回值:

*  **React elements.** 

*  **Arrays and fragments.**

*  **Portals**. return ReactDOM.createPortal(child, container)

*  **String and numbers.** These are rendered as text nodes in the DOM.

*  **Booleans or `null`**. Render nothing. (Mostly exists to support `return test && ` pattern, where `test` is boolean.)

constructor(props,context):初始化state和绑定方法的this作用域

1、If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

2、Avoid copying props into state! This is a common mistake:

The problem is that it’s both unnecessary (you can use this.props.color directly instead), and creates bugs (updates to the color prop won’t be reflected in the state).

componentDidMount(): is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

componentDidUpdate(prevProps,prevState,snapshot):is invoked immediately after updating occurs. 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. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If you’re trying to “mirror” some state to a prop coming from above, consider using the prop directly instead.If your component implements the getSnapshotBeforeUpdate() lifecycle (which is rare), the value it returns will be passed as a third “snapshot” parameter to componentDidUpdate(). Otherwise this parameter will be undefined.

https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html(合理把握props和state的转换关系),组件实例-ref

 when designing a component, it is important to decide whether its data will be controlled or uncontrolled.

你可能感兴趣的:(React生命周期理解)