作者:孫志勇
日期:2016年11月29日
一、時(shí)效性
所有信息都具有時(shí)效性。文章的價(jià)值,往往跟時(shí)間有很大關(guān)聯(lián)。特別是技術(shù)類文章,請(qǐng)注意本文創(chuàng)建時(shí)間,如果本文過于久遠(yuǎn),請(qǐng)讀者酌情考量,莫要浪費(fèi)時(shí)間。
二、背景
在學(xué)習(xí)React的過程中,頻繁的跟props和state打交道,對(duì)于初學(xué)者來說,不知道什么情況下來使用它們有時(shí)候不知道在什么情況下來使用它們。
三、相關(guān)性與區(qū)別
props和state之間是緊密相關(guān)的。父組件的state常常轉(zhuǎn)變子組件的props成下面我們通過一個(gè)父子組件從上至下來分析它們。
假如我們有個(gè)父組件,可以在父組件的state里定義子組件的數(shù)據(jù)比如:
this.setState({ childData: 'Child Data' });
緊接著,在父組件的render()方法里面,可以將父組件的state,作為子組件的props傳遞下去,如下
<Child data = {this.state.childData}/>
這樣就可以父組件的state傳遞給子組件的props。從子組件的角度來看,props是不可變的。如何改變子組件的props?我們僅僅需要改變父組件內(nèi)部的state即可,父組件的state改變之后,引起父組件重新渲染,在渲染的過程中,子組件的data變成父組件this.state.childDtat的值。這樣父組件內(nèi)部state改變,就會(huì)引起子組件的改變。
這樣就形成里從上而下的數(shù)據(jù)流,也就是React常說的單向數(shù)據(jù)流,這個(gè)“向”是向下。
我們常常利用這個(gè)原理更新子組件,從而衍生出一種模式,父組件:處理復(fù)雜的業(yè)務(wù)邏輯、交互以及數(shù)據(jù)等。子組件:稱它為Stateless組件即無狀態(tài)組件,只用作展示。在我們開發(fā)過程中,盡可能多個(gè)使用無狀態(tài)組件,可以縷清業(yè)務(wù)之間的邏輯關(guān)系,提高渲染效率。
如果子組件想要改變自身的data,這時(shí)候需要,父組件傳遞給子組件一個(gè)方法,改變父組件自身的state。
父組件:
<Child data={this.state.childData} handleChange={this.handelChildChange}></Child>
子組件接收父組件方法
let Chilid = ({data,handleChange}) =>
<div onClick={handleChange}>{data.name}</div>
四、完整代碼
父組件
import React, {Component} from 'react';
import Child from './components/child'
class App extends Component {
constructor(props) {
super(props);
this.state = {
childData: {name: 'child'}
};
this.handelChildChange = this.handelChildChange.bind(this);
}
handelChildChange(){
this.setState({
childData: {name: 'newChild'}
})
}
render() {
return (
<div style={{textAlign:'center'}}>
<Child data={this.state.childData} handleChange={this.handelChildChange}></Child>
</div>
);
}
}
export default App;
子組件:這里使用無狀態(tài)組件,解構(gòu)賦值以及無狀態(tài)組件使用父組件方法
import React from 'react';
let Chilid = ({data,handleChange}) =>
<div onClick={handleChange}>{data.name}</div>
export default Chilid
五、參考鏈接
- http://stackoverflow.com/questions/27991366/what-is-the-difference-between-state-and-props-in-react
- https://facebook.github.io/react/docs/state-and-lifecycle.html#the-data-flows-down
六、轉(zhuǎn)載分享
版權(quán)聲明:自由轉(zhuǎn)載-非商用-非衍生-保持署名(創(chuàng)意共享3.0許可證)