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的每一次改动都会使页面重新渲染一次。