React给state赋值赋值的两种方法

如果你看过React的官方文档,就会对怎么给局部state赋值有一定的了解。如下代码:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    date: new
Date()
  };

    this.handleClick = this.handleClick.bind(this);

  }
 handleClick(){
  alert('test');
 }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
     <button onClick={handleClick}>测试</button> </div> ); } }

 官方文档指出,如果你使用class组件并使用state、定义一些方法,那么需要注意以下3点:

  1. 需要在 class 构造函数 constructor中为 this.state 赋初值!
  2. 需要在 constructor中调用super(props),否则无法使用this.props;
  3. 在javascript中,class的方法默认不会绑定this, 如果你忘记绑定this.handleClick并把它传入了onClick,当你调用这个函数的时候this 的值是undefined.




但是,你是不是也见过这样的代码,如下:

class Clock extends React.Component {
   state = {
        date: new Date()
    };
  handleClick = ()=>{
    alert('test');
  } render() {
return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
     <button onClick={handleClick}>测试</button>  </div> ); } }

 它更简洁,不用以上注意以上三点,只要直接定义state对象中的变量即可(注意不是this.state),这是为什么呢?
  

 一个简单的方法可以比较两者写法到底有什么不同,那就是使用babel的Try it out 来验证下吧。为了output的代码更具可读性,所以我选择了es2016

 可以放大页面看,图片不能看原图

 第一种写法:

 第二种写法:



 对比babel转换后的代码可以看出,第二种写法其实state也是定义在了constructor中。


猜你喜欢

转载自www.cnblogs.com/hanlinbaiyu/p/12073474.html