Day 11 state & props -2

第十一天罗~

昨天我们说到 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>
  );
};

<<:  30-11 之Domain Layer - Transaction Script

>>:  分类模型哪个好?ROC/ AUC

被供应商和客户G爆时来一帖「资讯安全oo声明书」吧

资讯安全管理制度(ISMS)相关文件属於企业或机构内部资安治理运行标准与纪录,机密等级(控管标准)大...

卡夫卡的藏书阁【Book28】- Kafka - MirroMaker

“In man's struggle against the world, bet on the ...

管理职不是屎缺,但也不好做

相信这个问题做了几年工程师之後,应该多少都有想过一两次吧? 在管理职当然做的事情,就会从面对事情而转...

离职倒数24天:说出内心烦恼、学到新知识、得到新的角度,三个愿望一次满足

最近看了很多好书,看完的共通感想是,为什麽以前没人推荐我看这些?如果早点看,不知道可以少走多少弯路。...

Day 2 - 谈谈伦理骇客

出於书本 Chapter 1. Introduction to Ethical Hacking 骇客...