React学习之State

本文基于React v16.4.1

初学react,有理解不对的地方,欢迎批评指正^_^

一、定义组件的两种方式

1、函数定义组件

function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
}

2、类定义组件

class Welcome extends Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

  这两种方式都可以定义一个组件,区别在于类定义的组件有State和生命周期。另外,还要注意的是组件名称要以大写字母开头。

二、为组件添加State

如下,是官网的一个例子:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
  render() {
    return (
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
    );
  }
}

  可以看到,上面的代码在类中添加了constructor()方法,并在其中初始化了this.state 。

  关于constructor() :constructor()方法是类必须有的,如果没写,会自动添加。

  关于super(props) :super()方法将父类中的this对象继承给子类,添加参数props,就可以使用this.props 。

三、使用State

  1、不能直接修改State

初始化this.state只能在constructor()里面,修改State要用setState()方法。

2、可能是异步的

  调用setState,组件的state并不会立即改变,setState只是把要修改的状态放入一个队列中,React会优化真正的执行时机,并且React会出于性能原因,可能会将多次setState的状态修改合并成一次状态修改,所以不能用当前的state来计算下一个state。例如下面的写法是错误的:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});  

  应改为: 

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

  3、state的更新是浅合并的

例如,下面的state中有title和comments两个变量,当调用this.setState({title: 'react'})修改title时,react会把新的title合并进去,不会改变comment。           

constructor(props) {
    super(props);
    this.state = {
      title: 'abc',
      comments: []
    };
  }

END-------------------------------------

    

猜你喜欢

转载自www.cnblogs.com/MaiJiangDou/p/9240428.html