本文的实例demo主要涉及到 state状态机,组件的生命周期
react官网地址:React: A JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES
本文中的代码 github 地址:demo实例
demo的html模板
本文中所有的 demo ,都采用以下这个 html 模板:
|
|
demo6: state状态机
React 将组件划分为不同的状态,每个React组件实例都有一个state变量,用来保存组件的当前状态。state: 组件的状态变量;getInitialState(): 设置组件初始状态,必须返回一个JSON对象或空值null;setState(currentState): 设置组件当前状态,参数currentState是一个JSON对象;setState()方法会 将这个参数值与当前状态this.sate进行合并,结果作为状态变量的新值;不建议直接使用this.state来设置状态,setState()方法会自动 地重新渲染组件。
接下的demo实例,主要是设置初始化背景色、点击改变state状态进而改变背景色:
|
|
demo7: 组件的生命周期
组件实例的这个生命周期中,React 会在特定的时间点调用以下方法,触发的顺序如下表:
| First Render | Props Change | State Change | Unmount |
|---|---|---|---|
| getDefaultProps | componentWillReceiveProps | - | componentWillUnmount |
| getInitialState | shouldComponentUpdate | shouldComponentUpdate | - |
| componentWillMount | componentWillUpdate | componentWillUpdate | - |
| render | render | render | - |
| componentDidMount | componentDidUpdate | componentDidUpdate | - |
其中:componentWillMount():即将第一次render时候被调用,在整个生命周期中只会被调用一次(初次渲染)。componentDidMount:已经第一次render时候被调用,在整个生命周期中只会被调用一次(初次渲染)。componentWillReceiveProps(nextProps) :组件实例即将设置新属性时被调用,nextProps新属性值。shouldComponentUpdate(nextProps, nextState):组件实例即将重新渲染时被调用,但在初次渲染时或通过forceUpdate()方法进行渲染时不会被调用。componentWillUpdate(nextProps, nextState) :组件实例即将重新渲染时被调用,不能在此方法内调用 setState()。componentDidUpdate(prevProps, prevState):组件实例重新渲染后被调用。componentWillUnmount(): 组件实例即将从DOM树移除时被调用
这个方法在整个生命周期中只会被调用一次。
……
详尽的说明,请关注官网:组件的详细说明和生命周期
实例demo:通过设置定时器,触发组件被重复render,查看具体方法在不同时间点的调用情况:
|
|
更多学习demo,待续…
本文中的代码 github 地址:demo实例