iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
Modern Web

React Native & Redux 初步探討系列 第 11

Day 11 state & props -2

  • 分享至 

  • twitterImage
  •  

第十一天囉~

昨天我們說到 state , 那我們如何去改變 state 呢?

當我們直接改動 state , 會發現, 畫面根本不會更新

like:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      text: 'hello',
    };
  }

  onPressClickMe = () => {
    this.state.text = 'Wow~';
  };

  render() {
    return (
      <SafeAreaView>
        <View>
          <Button title='Click Me!!' onPress={this.onPressClickMe} />
          <Text>{this.state.text}</Text>
        </View>
      </SafeAreaView>
    );
  }
}

state

state 的改變需要跟隨著 component更新流程,這樣才會把更新的數據顯示在畫面上

那如何觸發更新流程呢?

setState

更新指定 state , 並觸發 component 的 update 的流程

this.setState(updater, [callback]);
  • updater 有兩種模式
    • object
      • 是以 key-value 方式來更新指定 state value
    • function
      • 是會接收當下的 state & props ,可以以此為參考基礎來進行更新, return object 包裹需要更改的值
  • callback 會在更新流程結束後去執行
//object
this.setState({ text: 'hello!' });

//function
this.setState(function (state, props) {
  return {
    text: 'hello',
  };
});

//use callback
this.setState(
  function (state, props) {
    return {
      text: 'hello',
    };
  },
  function () {
    console.log(this.state);
  }
);

所以,我們希望畫面隨著我們 state 值改變而改變,應該這樣做...

like:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      text: 'hello',
    };
  }

  onPressClickMe = () => {
    this.setState(() => {
      return {
        text: 'Wow~',
      };
    });
  };

  render() {
    return (
      <SafeAreaView>
        <View>
          <Button title='Click Me!!' onPress={this.onPressClickMe} />
          <Text>{this.state.text}</Text>
        </View>
      </SafeAreaView>
    );
  }
}

setState

component 內部進行更新流程的時候,

就會把底下有使用到的 component 一起更新

props

再來談到 props

當我們在開發時,總會考慮到 component 會在不同的情境上使用,

但是不可能把所有的邏輯都寫在 component 裡面,

這時我們就必須去靠 props 來讓外部有部分的控制權限 ,

那它的特性是:

  • 開發者 去定義外部能夠多大程度間接影響 component 的運作
  • 從外部傳入內部的參數都會放進 props 屬性裡,以物件key-value保存
  • 屬性是唯讀的,不能改動其值,也不應該在內部重新賦值給 props
  • 改變 props 值,只有在外部傳入的值發生改變時
  • 改變時會觸發 componentupdate 流程

設定

const TextBox = () => {
  return <Text>{this.props.value}</Text>;
};

使用

const App = () => {
  return (
    <SafeAreaView>
      <TextBox value={'Hello'} />
    </SafeAreaView>
  );
};

上一篇
Day 10 state & props -1
下一篇
Day 12 Component Lifecycle -1
系列文
React Native & Redux 初步探討33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言