React state&生命周期

本文详述了如何将React中的函数组件转换为Class组件,包括创建Class、迁移渲染逻辑及状态管理。同时,深入解析了Class组件的生命周期方法,如componentWillMount、render、componentDidMount等,并介绍了setState的正确使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将函数组件转化为class组件

通过五步将函数组件转化为class组件

  • 创建一个同名的 ES6 class,并且继承于 React.Component。
  • 添加一个空的 render() 方法。
  • 将函数体移动到 render() 方法之中。
  • 在 render() 方法中使用 this.props 替换 props。
  • 删除剩余的空函数声明。
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.date}</h1>;
  }
}

向 class 组件中添加局部的 state

通过三步将 date 从 props 移动到 state 中

  • 把 render() 方法中的 this.props.date 替换成 this.state.date
  • 添加一个 class 构造函数,然后在该函数中为 this.state 赋初值
  • 移除 元素中的 date 属性
class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
  render() {
    return <h1>Hello, {this.props.date}</h1>;
  }
}
ReactDOM.render(
  <Welcome />,
  document.getElementById('root')
);

将生命周期方法添加到 Class 中

第一个是组件初始化(initialization)阶段

constructor()用来做一些组件的初始化工作,如定义this.state的初始内容
super(props)用来调用基类的构造方法( constructor() ), 也将父组件的props注入给子组件,功子组件读取(组件中props只读不可变,state可变)

constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
第二个组件的挂载(Mounting)阶段

此阶段分为componentWillMount,render,componentDidMount三个时期。

  • componentWillMount:
    在组件挂载到DOM前调用,且只会被调用一次
componentWillMount()
  • render:
    根据组件的 propsstate , return 一个 React 元素
  • componentDidMount:
    组件挂载到DOM后调用,且只会被调用一次,可以在这里设置定时器。
componentWillReceiveProps(nextProps)
  • 定时器可以在componentWillUnmount()中进行清楚
componentWillUnmount() {
    clearInterval(this.timerID);
  }
第三个是组件的更新(update)阶段
  • 组件挂载之后,每次调用setState后都会调用shouldComponentUpdate判断是否需要重新渲染组件。默认返回true,需要重新render。在比较复杂的应用里,有一些数据的改变并不影响界面展示,可以在这里做判断,优化渲染效率
shouldComponentUpdate(nextProps, nextState)
  • shouldComponentUpdate返回true或者调用forceUpdate之后,componentWillUpdate会被调用。
componentWillUpdate(nextProps, nextState)
  • 除了首次render之后调用componentDidMount,其它render结束之后都是调用componentDidUpdate。
componentDidUpdate()

正确的使用state

  • 首先不要直接修改state,因为这样不会重新渲染组件
this.state.comment = 'Hello';//错误

应该使用 setState

this.setState({comment: 'Hello'});//正确
  • State 的更新可能是异步的
    因为 this.props 和 this.state 可能会异步更新,所以最好不要依赖他们的值来更新下一个状态。
    解决这个问题,可以让 setState() 接收一个函数而不是一个对象
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));
  • State 的更新会被合并
    当你调用 setState() 的时候,React 会把你提供的对象合并到当前的 state,也就是说,当我们通过setState来修改了state中的某一个数据,那么state原数据会和最新数据进行合并。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值