5 - state & 生命周期

state (状态)

与 props (属性) 相似,但 state 是私有的,只属于当前组件。

1. 状态的定义、使用与更新

class Hello extends React.Component {
  constructor (props) {
    super(props);

    // 定义状态
    this.state = {
      name: 'hello'
    }
  }
  render () {
    // 通过 this.state 使用状态
    return (
      <div>
        <h1>hello, { this.state.name }</h1>
        {/* 通过调用 this.setState 来修改状态 */}
        <button onClick={ () => { this.setState({ name: 'world' }) } }>修改name</button>
      </div>
    )
  }
}

上面代码中,

  • 通过在 constructor 中设置 this.state 来定义状态。
    并且 constructor 是唯一能够初始化状态的地方。
    constructor 必须使用 super() 调用基础构造函数。
  • 通过 this.state.xxx 来使用某个状态。
  • 通过 this.setState() 来修改状态。

2. 正确的使用状态

  • 不要直接更新状态
  • 状态更新可能是异步的
  • 状态更新合并

PS

  • 函数定义的组件又叫无状态组件,so,想给某个组件添加状态,需要使用类组件的方式

生命周期

1. 生命周期图解

image.png

2. 生命周期介绍

  • constructor(props) - 构造函数
  • componentWillMount() - 组件挂载之前
  • render() - 渲染
  • componentDidMount() - 组件挂载完成
  • componentWillReceiveProps(nextProps) - 组件接收到新属性前调用
  • shouldComponentUpdate(nextProps, nextState) - 我是否应该要更新呢
  • componentWillUpdate(nextProps, nextState) - 组件更新之前
  • componentDidUpdate(prevProps, prevState) - 组件更新完成
  • componentWillUnmount() - 组件卸载之前

3. 通过 shouldComponentUpdate(nextProps, nextState) 来处理一些性能问题

组件的某一些状态或属性的改变可能不需要进行页面的更新。此时在 shouldComponentUpdate() 中返回 false 即可。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容