React组件的状态及生命周期事件

本文介绍了React中组件的两种定义方式:函数定义和类定义,并详细解释了类定义组件如何管理和更新状态,包括正确的setState使用方法及注意事项。

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

定义组件

组件定义有两种方式,函数定义和类定义

函数定义组件

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

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

类定义组件

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
ReactDOM.render(
  <Welcome name="kevin" />,
  document.getElementById('root')
);

警告:

组件的返回值只能有一个根元素。如果ReactDOM.render方法渲染组件里包含多个同级别的组件,需要用一个DIV将其他组件包裹

类定义组件有局部状态和生命周期钩子事件

通常类的状态是在类的构造函数中声明的

class Clock extends React.Component {
  constructor(props) {
    super(props);//只要类组件声明了构造函数就必须先调用父类的构造函数
    this.state = {date: new Date()};
  }

  //更新状态
  this.setState({
      date: new Date()
  });
}

警告:

如果你不在 render() 中使用某些东西,它就不应该在状态中

钩子函数

componentDidMount(当组件插入到DOM中触发)
componentWillUnmount(当组件移出DOM中后触发)

正确使用状态

1.不要直接更新状态,而是通过setState方法

// Wrong
this.state.comment = 'Hello';

// Correct
this.setState({comment: 'Hello'});

2.状态的更新可能是异步的,你不应该依靠它们的值来计算下一个状态

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

当要被更新的状态依赖于props或它自身时,setState需要传递一个方法作为参数,第一个参数为它的前一个状态的值,第二个参数为props对象
// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值