iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 12
0
Modern Web

RRRR的世界 (Ruby on Rails + React + Redux)系列 第 12

Day 12, React props and state 藏在component裡的變數

今天終於要開始講ReactJs了,我選擇先把Props跟State先講,因為這會關係到component的重新生成(re-render)。
好!先看看之前的HelloWorld範例:

import React, { PropTypes } from 'react';
import HelloWorldWidget from '../components/HelloWorldWidget';

const propTypes = {
  name: PropTypes.string.isRequired, 
};
class HelloWorld extends React.Component {
//  static propTypes = {
//    name: PropTypes.string.isRequired, 
//  };
  constructor(props, context) {
    super(props, context);
    this.state = { name: this.props.name };
  }
  updateName(name) {
    this.setState({ name });
  }
  render() {
    return (
      <div>
        <HelloWorldWidget name={this.state.name} updateName={e => this.updateName(e)} />
      </div>
    );
  }
}
HelloWorld.propTypes = propTypes;
export default HelloWorld;

我稍微改寫了一下,把static搬到外面宣告,然後在最後assign

先讓我講state

如果沒有特別設定的話,state的改變就會影響到component的狀態,勢必會重新render。
在component中要使用state的話,最好先在constructor中宣告

constructor(props, context){
  this.state = { name: this.props.name };
}

這樣子,this.state.name就可以在之後被你讀取到。但是要改寫的話千萬不要直接assign,要透過setState function才行:

this.setState({ name });
// 等於 this.setState({name: name})

經過set以後(一小段時間),component就會重新再生成一次。

你要不要試試看set的東西並沒有在render裡用到,會不會render?

state對我而言是一種變數,哪時候會用到state,就好像哪時候會用到這種變數的問題一樣。
它使用於component內部,並且改變他會重新render component

再讓我講props

這邊就先問:哪時候會使用到props這種變數?
它使用於component外部,讓parent改變他,並會重新render component

我因為Airbnb coding style所以改寫了他,這部分後續應該會再多一天來講。

先看class上面宣告的const props

const propTypes = {
  name: PropTypes.string.isRequired, 
};

宣告了一個string的name準備給外面的component傳入字串,isRequired是說一定需要用到。
有哪些型態,請看這裡>>(https://facebook.github.io/react/docs/typechecking-with-proptypes.html),裡面的都還滿常用的。

接下來要跳到後面:
HelloWorld.propTypes = propTypes;
把宣告的propTypes assign到HelloWorld的static propTypes裡面去。

最後就是constructor裡有個參數(props, context),去接收第一次被render時傳入的props

constructor(props, context){
  this.state = { name: this.props.name };
}

沒意外的話,Parent有改變child props的時候,child component都會重新render!

今天快速的講了props跟state,我說了兩次”沒意外的話“,就是明天要講的內容了!
希望有看的人這幾天都看得懂我在寫什麼~。
好,打完收工!


上一篇
Day 11, 兩個React_on_rails範例
下一篇
Day 13, React Lifecycle 不搞懂就掰了
系列文
RRRR的世界 (Ruby on Rails + React + Redux)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言