react的props及state详解

react

props && state && 生命周期

State和props类似,但是它是私有的,并且完全由component控制
实力对比props和state
1.props

function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}
function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}
setInterval(tick, 1000);

2. state

class Clock extends React.Component {  // 对象继承至React.component
  constructor(props) {
    super(props);
    this.state = {date: new Date()};  // 构造函数提供初始值,state是一个对象
  }
  componentDidMount() {  // 生命周期钩子,在component在DOM中渲染完成之后执行
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }
  componentWillUnmount() { // 生命周期钩子,在component即将销毁时执行
    clearInterval(this.timerID);
  }
  tick() {
    this.setState({  // 修改component的state
      date: new Date()
    });
  }
  render() {  // class返回一个render
    return (  // render返回一个“(element)”
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2> // Js表达式中使用this.state
      </div>
    );
  }
}
ReactDOM.render(
  <Clock />,  // clock中移除date
  document.getElementById('root')
);`

state的使用及修改
使用setState修改state
setState可以传入两个参数:prevState, props(前一个状态、参数)

this.setState((prevState, props) => ({ 
  counter: prevState.counter + props.increment
}));

state的修改会被合并,可以理解为执行一个Object.assign(oldState, newState)操作

可以将state作为props传递给child component(子组件),state只会向下传递

<FormattedDate date={this.state.date} />
function FormattedDate(props) {
  return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}

需注意的是state,props的每一次改动都会使页面重新渲染一次。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值