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

简介: State and Lifecycle何谓stateA 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

搞懂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')
);
目录
相关文章
|
3月前
|
前端开发
react生命周期的一些坑
react生命周期的一些坑
|
3月前
|
前端开发 JavaScript 开发者
【第27期】一文了解React生命周期
【第27期】一文了解React生命周期
32 0
|
3月前
|
前端开发
React中生命周期的讲解
React中生命周期的讲解
|
17天前
|
前端开发 JavaScript
React生命周期方法在实际开发中的应用场景有哪些?
【4月更文挑战第6天】 React 生命周期方法应用于数据获取、订阅管理、渲染逻辑处理、用户交互响应、性能优化、资源清理、强制更新、错误处理、动画实现、代码分割、服务端渲染、路由处理、依赖注入和集成第三方库。它们帮助控制组件行为和性能,但现代开发推荐使用Hooks替代部分生命周期方法。
15 0
|
1月前
react+typescript给state和props定义指定类型
react+typescript给state和props定义指定类型
16 1
|
3月前
|
前端开发
React旧有生命周期和新生命周期的解析
React旧有生命周期和新生命周期的解析
29 0
React旧有生命周期和新生命周期的解析
|
3月前
|
前端开发 JavaScript API
React组件生命周期
React组件生命周期
74 1
|
3月前
|
前端开发
「React」很多人在滥用 state
「React」很多人在滥用 state
|
3月前
|
前端开发 JavaScript 测试技术
第十三章 React生命周期(新)
第十三章 React生命周期(新)
|
4月前
|
前端开发 JavaScript
react 生命周期函数
react 生命周期函数