react基礎(chǔ)

生命周期相關(guān)函數(shù)

 生命周期共提供了10個(gè)不同的API。

1.getDefaultProps
  作用于組件類,只調(diào)用一次,返回對(duì)象用于設(shè)置默認(rèn)的props,對(duì)于引用值,會(huì)在實(shí)例中共享。

2.getInitialState
  作用于組件的實(shí)例,在實(shí)例創(chuàng)建時(shí)調(diào)用一次,用于初始化每個(gè)實(shí)例的state,此時(shí)可以訪問this.props。

3.componentWillMount
  在完成首次渲染之前調(diào)用,此時(shí)仍可以修改組件的state。

4.render
  必選的方法,創(chuàng)建虛擬DOM,該方法具有特殊的規(guī)則:
  只能通過this.props和this.state訪問數(shù)據(jù)
  可以返回null、false或任何React組件
  只能出現(xiàn)一個(gè)頂級(jí)組件(不能返回?cái)?shù)組)
  不能改變組件的狀態(tài)
  不能修改DOM的輸出

5.componentDidMount
  真實(shí)的DOM被渲染出來(lái)后調(diào)用,在該方法中可通過this.getDOMNode()訪問到真實(shí)的DOM元素。此時(shí)已可以使用其他類庫(kù)來(lái)操作這個(gè)DOM。
  在服務(wù)端中,該方法不會(huì)被調(diào)用。

6.componentWillReceiveProps
    組件接收到新的props時(shí)調(diào)用,并將其作為參數(shù)nextProps使用,此時(shí)可以更改組件props及state。

    componentWillReceiveProps: function(nextProps) {
        if (nextProps.bool) {
            this.setState({
                bool: true
            });
          }
      }

7.shouldComponentUpdate
    組件是否應(yīng)當(dāng)渲染新的props或state,返回false表示跳過后續(xù)的生命周期方法,通常不需要使用以避免出現(xiàn)bug。在出現(xiàn)應(yīng)用的瓶頸時(shí),可通過該方法進(jìn)行適當(dāng)?shù)膬?yōu)化。

    在首次渲染期間或者調(diào)用了forceUpdate方法后,該方法不會(huì)被調(diào)用

8.componentWillUpdate
    接收到新的props或者state后,進(jìn)行渲染之前調(diào)用,此時(shí)不允許更新props或state。

9.componentDidUpdate
    完成渲染新的props或者state后調(diào)用,此時(shí)可以訪問到新的DOM元素。

10.componentWillUnmount
     組件被移除之前被調(diào)用,可以用于做一些清理工作,在componentDidMount方法中添加的所有任務(wù)都需要在該方法中撤銷,比如創(chuàng)建的定時(shí)器或添加的事件監(jiān)聽器。
image.png

生命周期簡(jiǎn)單模板

class name extend component{
    static defluteProps={
        name:'name',
    },
   constructor(props){
      super(props);
      this.state={.......}
    },
  componmentsWillmount(){

  },
  doSomething = () => {
      require.ensure(['./app2',....], (require) => {
          const Comp = require('./app2');
          this.setState({
              currentComponent: <Comp/>
          })
      })
  };
  render(){
      render(){
        <div>{this.state}</div>
    }
  } 
}

組件之間傳值

  • 父組件 向 子組件 傳遞信息 >>>主要是通過 prop進(jìn)行傳值
<span style="font-size:18px;">//父組件  
var MyContainer = React.createClass({  
  getInitialState: function () {  
    return {  
      checked: false  
    };  
  },  
  render: function() {  
    return (  
      <ToggleButton text="Toggle me" checked={this.state.checked} />  
    );  
  }  
});  
  
// 子組件  
var ToggleButton = React.createClass({  
  render: function () {  
    // 從(父組件)獲取的值  
    var checked = this.props.checked,  
        text = this.props.text;  
  
    return (  
        <label>{text}: <input type="checkbox" checked={checked} /></label>  
    );  
  }  
});</span>  
  • 子組件 向 父組件 傳遞信息
<span style="font-size:18px;">// 父組件  
var MyContainer = React.createClass({  
  getInitialState: function () {  
    return {  
      checked: false  
    };  
  },  
  onChildChanged: function (newState) {  
    this.setState({  
      checked: newState  
    });  
  },  
  render: function() {  
    var isChecked = this.state.checked ? 'yes' : 'no';  
    return (  
      <div>  
        <div>Are you checked: {isChecked}</div>  
        <ToggleButton text="Toggle me"  
          initialChecked={this.state.checked}  
          callbackParent={this.onChildChanged}  
          />  
      </div>  
    );  
  }  
});  
  
// 子組件  
var ToggleButton = React.createClass({  
  getInitialState: function () {  
    return {  
      checked: this.props.initialChecked  
    };  
  },  
  onTextChange: function () {  
    var newState = !this.state.checked;  
    this.setState({  
      checked: newState  
    });  
  
    //這里將子組件的信息傳遞給了父組件  
    this.props.callbackParent(newState);  
  },  
  render: function () {  
    // 從(父組件)獲取的值  
    var text = this.props.text;  
    // 組件自身的狀態(tài)數(shù)據(jù)  
    var checked = this.state.checked;  
        //onchange 事件用于單選框與復(fù)選框改變后觸發(fā)的事件。  
    return (  
        <label>{text}: <input type="checkbox" checked={checked} onChange={this.onTextChange} /></label>  
    );  
  }  
});</span>  

以上例子中,在父組件綁定callbackParent={this.onChildChanged},在子組件利用this.props.callbackParent(newState),觸發(fā)了父級(jí)的的this.onChildChanged方法,進(jìn)而將子組件的數(shù)據(jù)(newState)傳遞到了父組件。
這樣做其實(shí)是依賴 props 來(lái)傳遞事件的引用,并通過回調(diào)的方式來(lái)實(shí)現(xiàn)的。
  • 兄弟組件之間的傳值
  <span style="font-size:18px;">// 定義一個(gè)容器(將ProductSelection和Product組件放在一個(gè)容器中)  
var ProductList = React.createClass({  
    render: function () {  
      return (  
        <div>  
          <ProductSelection />  
          <Product name="product 1" />  
          <Product name="product 2" />  
          <Product name="product 3" />  
        </div>  
      );  
    }  
});  
// 用于展示點(diǎn)擊的產(chǎn)品信息容器  
var ProductSelection = React.createClass({  
  getInitialState: function() {  
    return {  
      selection: 'none'  
    };  
  },  
  componentDidMount: function () {  
    //通過PubSub庫(kù)訂閱一個(gè)信息  
    this.pubsub_token = PubSub.subscribe('products', function (topic, product) {  
      this.setState({  
        selection: product  
      });  
    }.bind(this));  
  },  
  componentWillUnmount: function () {  
    //當(dāng)組件將要卸載的時(shí)候,退訂信息  
    PubSub.unsubscribe(this.pubsub_token);  
  },  
  render: function () {  
    return (  
      <p>You have selected the product : {this.state.selection}</p>  
    );  
  }  
});  
  
var Product = React.createClass({  
  onclick: function () {  
    //通過PubSub庫(kù)發(fā)布信息  
    PubSub.publish('products', this.props.name);  
  },  
  render: function() {  
    return <div onClick={this.onclick}>{this.props.name}</div>;  
  }  
});</span>  
這個(gè)例子需要引入一個(gè)PubSubJS 庫(kù),通過這個(gè)庫(kù)你可以訂閱的信息,發(fā)布消息以及消息退訂。
ProductSelection和Product本身是沒有嵌套關(guān)系的,而是兄弟層級(jí)的關(guān)系。但通過在ProductSelection組件中訂閱一個(gè)消息,在Product組件中又發(fā)布了這個(gè)消息,使得兩個(gè)組件又產(chǎn)生了聯(lián)系,進(jìn)行傳遞的信息。所以根據(jù)我個(gè)人的理解,當(dāng)兩個(gè)組件沒有嵌套關(guān)系的時(shí)候,也要通過全局的一些事件等,讓他們聯(lián)系到一起,進(jìn)而達(dá)到傳遞信息的目的。
  • 利用react-redux進(jìn)行組件之間的狀態(tài)信息共享

require.ensure()按需加載

require.ensure(dependencies: String[], callback: function([require]), [chunkName: String])
 dependencies: 依賴的模塊數(shù)組
 callback: 回調(diào)函數(shù),該函數(shù)調(diào)用時(shí)會(huì)傳一個(gè)require參數(shù)
 chunkName: 模塊名,用于構(gòu)建時(shí)生成文件時(shí)命名使用

路由配置模板

    const RouteConfig = (
        <Router history={history}>
            <Route path="/" component={Roots}>
                <IndexRoute component={index} />//首頁(yè)
                <Route path="index" component={index} />
                <Route path="helpCenter" getComponent={helpCenter} />//幫助中心
                <Route path="saleRecord" getComponent={saleRecord} />//銷售記錄
                <Redirect from='*' to='/'  />
            </Route>
        </Router>
    );

fetch 簡(jiǎn)單使用 第二個(gè)參數(shù)為可選

 var myHeaders = new Headers();
 var myInit = { 
               method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' 
              };

  fetch(url,myInit).then(function(response) {
                             return response.blob();
                        }).then(function(myBlob) {
                            var objectURL = URL.createObjectURL(myBlob);
                            myImage.src = objectURL;
                        });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容