搞懂React的state和生命周期函数(lifecycle methods)

State and Lifecycle

何谓state

A component needs state when some data associated with it changes over time. For example, a Checkbox component might need isChecked in its state,

  • 组件内部涉及的数据会根据时间条件变化

  • 随着数据的变化,要相应的更新DOM

  • 此时:需要使用state去接收这些不断变化的数据,然后通过setState更新DOM

何谓Lifecycle methods

Lifecycle methods are custom functionality that gets executed during the different phases of a component. There are methods available when the component gets created and inserted into the DOM (mounting), when the component updates, and when the component gets unmounted or removed from the DOM

  • 组件的生命周期即组件从被创建、渲染插入DOM,从DOM中移除所经历的阶段

  • 每个阶段都有对应的函数,你可以去做相应的操作,比如下面demo中,componentDidMount函数在组件被渲染进DOM时调用,componentWillUnmount函数在组件从DOM中移除时调用

state VS props

The most important difference between state and props is that props are passed from a parent component, but state is managed by the component itself. A component cannot change its props, but it can change its state.

  • props是由外部传入组件的,组件不能改变props
  • state是在组件内部进行管理的,组件可以改变 state

何谓单向数据流

父组件可以向子组件传值,反之不行。比如下面DEMO中:父组件Clock将自己state中存的date的值传给了子组件FormattedDate

官网DEMO:

// 子组件
function FormattedDate(props) {
  return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
 
   // 生命周期函数
  componentDidMount() {  
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <FormattedDate date={this.state.date} />
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

更多讨论issues

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值