函数式(Function)组件
http://www.css88.com/react/docs/components-and-props.html
组件名称以大写字母开始
所有React组件都必须是纯函数,并禁止修改其自身props
functionWelcome(props){
returnHello,{props.name};
}
constelement=;
ReactDOM.render(
element,
document.getElementById('root')
);
类组件
栗子1:
classClockextendsReact.Component{
constructor(props){// 唯一可以分配 this.state 的地方是构造函数
super(props);
this.state={
date:newDate(),
comments: []
};
}
componentDidMount(){// 挂载(mounting):第一次渲染DOM
this.timerID=setInterval(()=>this.tick(),1000); // 设置定时器,周期性的更新组件
fetchComments().then(response=>{// ----------1
this.setState({// 浅合并,只会完全替换 this.state.comments 的值,不会改变改变其他的值
comments:response.comments
});
});
}
componentWillUnmount(){// 卸载(unmounting):产生的DOM被销毁
clearInterval(this.timerID); // 销毁定时器
}
render(){
return(
Hello,world!
//// ----------- 2 // 替换
);
}
}
ReactDOM.render(
tick(){
this.setState({// 不要直接修改state(状态),要用 setState()代替
date:newDate()
});
}
document.getElementById('root')
);
state(状态)
不要直接修改state,要用 setState()代替,唯一可以分配 this.state 的地方是构造函数
state更新会被合并:浅合并 => 看栗子1 --- 1
state 更新可能是异步的
react 为了优化性能,可能将多个setState()调用合并为一次更新
因为 this.props 和 this.state 可能是异步更新的,你不能依赖他们的值计算下一个state
错误写法:this.setState()
正确写法
第一个参数:接收的前一个状态
第二个参数:应用更新时的props
this.setState((prevState,props)=>({
counter:prevState.counter+props.increment
})
);
数据向下流动(单向数据流)
一个组件可以选择将state向下传递,作为其子组件的props(属性)=> 栗子1 --- 2
functionFormattedDate(props){
}
领取专属 10元无门槛券
私享最新 技术干货