設定狀態:setState
替換狀態:replaceState
設定屬性:setProps
替換屬性:replaceProps
強制更新:forceUpdate
獲取DOM節點:findDOMNode
判斷組件掛載狀態:isMounted
1、關于setState
不能在組件內部通過this.state修改狀態,因為該狀態會在呼叫setState()后被替換,
setState()并不會立即改變this.state,而是創建一個即將處理的state,setState()并不一定是同步的,為了提升性能React會批量執行state和DOM渲染,
setState()總是會觸發一次組件重繪,除非在shouldComponentUpdate()中實作了一些條件渲染邏輯,
【計時器實體】
import React, { Component,Fragment } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import PropTypes from 'prop-types';
class Clock extends Component{
constructor(props){
super(props);
this.state={
countNum:0
}
this.addCount=this.addCount.bind(this);
}
addCount(){
this.setState({
countNum:this.state.countNum+1
})
}
render(){
return(
<Fragment>
<button onClick={this.addCount}>點擊計數</button>
<p>{this.state.countNum}</p>
</Fragment>
)
}
}
ReactDOM.render(
<div>
<Clock />
</div>,
document.getElementById('example')
);
serviceWorker.unregister();

關于 setState() 這里有三件事情需要知道,
1、不要直接更新狀態
例如,此代碼不會重新渲染組件:
this.state.comment = 'Hello';
應當使用 setState():
this.setState({comment: 'Hello'});
建構式是唯一能夠初始化 this.state 的地方,
2、狀態更新可能是異步的
因為 this.props 和 this.state 可能是異步更新的,不能根據它們的值來計算下一個狀態,
例如,此代碼可能無法更新計數器:
// Wrong this.setState({ counter: this.state.counter + this.props.increment, });
正確的打開方式:
接收先前的狀態作為第一個引數,將此次更新被應用時的props做為第二個引數:
// Correct this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));
3、狀態更新合并
當你呼叫 setState() 時,React 將你提供的物件合并到當前狀態,
例如,你的狀態可能包含一些獨立的變數:
constructor(props) { super(props); this.state = { posts: [], comments: [] }; } componentDidMount() { fetchPosts().then(response => { this.setState({ posts: response.posts }); }); fetchComments().then(response => { this.setState({ comments: response.comments }); }); }
2、replaceState()方法與setState()類似,但是方法只會保留nextState中狀態,原state不在nextState中的狀態都會被洗掉,
3、props相當于組件的資料流,它總是會從父組件向下傳遞至所有的子組件中,當和一個外部的JavaScript應用集成時,我們可能會需要向組件傳遞資料或通知React.render()組件需要重新渲染,可以使用setProps(),
更新組件,可以在節點上再次呼叫React.render(),也可以通過setProps()方法改變組件屬性,觸發組件重新渲染,
4、replaceProps()方法與setProps類似,但它會洗掉原有 props,
5、forceUpdate()方法會使組件呼叫自身的render()方法重新渲染組件,組件的子組件也會呼叫自己的render(),但是,組件重新渲染時,依然會讀取this.props和this.state,如果狀態沒有改變,那么React只會更新DOM,
forceUpdate()方法適用于this.props和this.state之外的組件重繪(如:修改了this.state后),通過該方法通知React需要呼叫render()
一般來說,應該盡量避免使用forceUpdate(),而僅從this.props和this.state中讀取狀態并由React觸發render()呼叫,
如果組件已經掛載到DOM中,該方法回傳對應的本地瀏覽器 DOM 元素,當render回傳null 或 false時,this.findDOMNode()也會回傳null,從DOM 中讀取值的時候,該方法很有用,如:獲取表單欄位的值和做一些 DOM 操作,
6、isMounted()方法用于判斷組件是否已掛載到DOM中,可以使用該方法保證了setState()和forceUpdate()在異步場景下的呼叫不會出錯,
isMounted 的方法在 ES6 中已經廢除,主要的原因是它經過實際使用與測驗可能不足以檢測組件是否掛載,尤其是對于有一些異步的程式情況,以及邏輯上造成混亂,現在用以下方法代替:
componentDidMount() { this.mounted = true; } componentWillUnmount() { this.mounted = false; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/123536.html
標籤:JavaScript
