将函数组件转换为函数组件
- 创建一个同名的类组件并且继承React.Compoent
- 添加一个空的方法叫做render()
- 把函数里面的内容移到render方法里面
- 把render()里面的props替换成this.props
- 删掉之前的函数声明的组件
//最后执行第5步,删掉函数声明的组件,这里作为演示,所有不做删除
function Welcome(props){
return <h1>Hello {1 + props.num}</h1>
}
class Welcome extends React.Component {
render(){
<h1>Hello {1 + this.props.num}</h1>
}
}
state状态
在官网的例子中,当前学到更新UI的方式是重新创建一个element,并render到页面中。在这里将使用state来实现UI更新。
state和props很相似,但state是属于组件私有的属性,并且可以改变的
添加state
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
生命周期
componentDidMount 组件挂载后执行(渲染到dom节点)
componentWillUnmount 组件卸载后执行
正确使用state
- 官方建议修改state使用 setState方法 this.setState({comment: 'Hello'});
- 唯一声明state仅限在contructor中进行
更新state
更新state是一个异步的过程,如果依赖他们的值来计算下一个state,则可能会出现错误
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
为了解决这个问题,让setState()接收一个函数比接收一个对象的方式更好。
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
等价于
this.setState(function(prevState, props) {
return {
counter: prevState.counter + props.increment
};
});
单向数据流
在react中无论父组件还是子组件都无法知道其他组件的状态,子组件可以接受父组件传递的数据,父组件可以通过状态选择子组件,这样的自上而下的数据流向,称为单向数据流。
网友评论